Formatieren von Antwortdaten in Web-APIs in ASP.NET CoreFormat response data in ASP.NET Core Web API
Von Rick Anderson und Steve SmithBy Rick Anderson and Steve Smith
ASP.NET Core MVC unterstützt das Formatieren von Antwortdaten.ASP.NET Core MVC has support for formatting response data. Antwortdaten können mithilfe bestimmter Formate oder durch Übernahme des vom Client angeforderten Formats formatiert werden.Response data can be formatted using specific formats or in response to client requested format.
Anzeigen oder Herunterladen von Beispielcode (Vorgehensweise zum Herunterladen)View or download sample code (how to download)
Formatspezifische AktionsergebnisseFormat-specific Action Results
Einige Aktionsergebnistypen sind für ein bestimmtes Format spezifisch, wie z.B. JsonResult und ContentResult.Some action result types are specific to a particular format, such as JsonResult and ContentResult. Aktionen können Ergebnisse zurückgeben, die in einem bestimmten Format formatiert sind, unabhängig von den Clienteinstellungen.Actions can return results that are formatted in a particular format, regardless of client preferences. Mit JsonResult
beispielsweise werden JSON-formatierte Daten zurückgegeben.For example, returning JsonResult
returns JSON-formatted data. Mit ContentResult
oder einer Zeichenfolge werden Zeichenfolgendaten in Nur-Text-Format zurückgegeben.Returning ContentResult
or a string returns plain-text-formatted string data.
Zum Zurückgeben eines bestimmten Typs ist keine Aktion erforderlich.An action isn't required to return any specific type. ASP.NET Core unterstützt jeden Objektrückgabewert.ASP.NET Core supports any object return value. Ergebnisse von Aktionen, die Objekte zurückgeben, deren Typ nicht IActionResult ist, werden mit der entsprechenden IOutputFormatter-Implementierung serialisiert.Results from actions that return objects that are not IActionResult types are serialized using the appropriate IOutputFormatter implementation. Weitere Informationen finden Sie unter Rückgabetypen für Controlleraktionen in der ASP.NET Core-Web-API.For more information, see Rückgabetypen für Controlleraktionen in der ASP.NET Core-Web-API.
Die integrierte Hilfsmethode Ok gibt JSON-formatierte Daten zurück: [!code-csharp]The built-in helper method Ok returns JSON-formatted data: [!code-csharp]
Der Beispieldownload gibt die Liste der Autoren zurück.The sample download returns the list of authors. Bei Verwendung der F12-Entwicklertools im Browser oder von Postman mit dem obigen Code gilt Folgendes:Using the F12 browser developer tools or Postman with the previous code:
- Der Antwortheader mit content-type:
application/json; charset=utf-8
wird angezeigt.The response header containing content-type:application/json; charset=utf-8
is displayed. - Die Anforderungsheader werden angezeigt.The request headers are displayed. Beispiel: Der Header
Accept
.For example, theAccept
header. DerAccept
-Header wird vom vorangehenden Code ignoriert.TheAccept
header is ignored by the preceding code.
Wenn Sie Daten im Textformat zurückgeben möchten, verwenden Sie ContentResult und das Content-Hilfsprogramm:To return plain text formatted data, use ContentResult and the Content helper:
// GET api/authors/about
[HttpGet("About")]
public ContentResult About()
{
return Content("An API listing authors of docs.asp.net.");
}
Im obigen Code wird text/plain
als Content-Type
zurückgegeben.In the preceding code, the Content-Type
returned is text/plain
. Das Zurückgeben einer Zeichenfolge liefert text/plain
als Content-Type
:Returning a string delivers Content-Type
of text/plain
:
// GET api/authors/version
[HttpGet("version")]
public string Version()
{
return "Version 1.0.0";
}
Bei Aktionen mit mehreren Rückgabetypen wird IActionResult
zurückgegeben.For actions with multiple return types, return IActionResult
. Beispiel: Die Rückgabe von verschiedenen HTTP-Statuscodes basierend auf dem Ergebnis der ausgeführten Vorgänge.For example, returning different HTTP status codes based on the result of operations performed.
InhaltsaushandlungContent negotiation
Eine Inhaltsaushandlung tritt auf, wenn der Client einen Accept-Header angibt.Content negotiation occurs when the client specifies an Accept header. Das von ASP.NET Core verwendete Standardformat ist JSON.The default format used by ASP.NET Core is JSON. Für die Inhaltsaushandlung gilt:Content negotiation is:
- Sie wird durch ObjectResult implementiert.Implemented by ObjectResult.
- Sie ist in die Statuscode-spezifischen Aktionsergebnisse integriert, die von den Hilfsmethoden zurückgegeben werden.Built into the status code-specific action results returned from the helper methods. Die Hilfsmethoden für Aktionsergebnisse basieren auf
ObjectResult
.The action results helper methods are based onObjectResult
.
Wenn ein Modelltyp zurückgegeben wird, lautet der Rückgabetyp ObjectResult
.When a model type is returned, the return type is ObjectResult
.
Die folgende Aktionsmethode verwendet die Hilfsmethoden Ok
und NotFound
:The following action method uses the Ok
and NotFound
helper methods:
// GET: api/authors/search?namelike=th
[HttpGet("Search")]
public IActionResult Search(string namelike)
{
var result = _authors.GetByNameSubstring(namelike);
if (!result.Any())
{
return NotFound(namelike);
}
return Ok(result);
}
Standardmäßig unterstützt ASP.NET Core application/json
-, text/json
- und text/plain
-Medientypen.By default, ASP.NET Core supports application/json
, text/json
, and text/plain
media types. Tools wie Fiddler oder Postman können den Accept
-Anforderungsheader festlegen, um das Rückgabeformat anzugeben.Tools such as Fiddler or Postman can set the Accept
request header to specify the return format. Wenn der Accept
-Header einen vom Server unterstützten Typ enthält, wird dieser Typ zurückgegeben.When the Accept
header contains a type the server supports, that type is returned. Der nächste Abschnitt zeigt, wie zusätzliche Formatierer hinzugefügt werden.The next section shows how to add additional formatters.
Controlleraktionen können POCOs (Plain Old CLR Objects) zurückgeben.Controller actions can return POCOs (Plain Old CLR Objects). Wenn ein POCO zurückgegeben wird, erstellt die Runtime automatisch ein ObjectResult
, das das Objekt umschließt.When a POCO is returned, the runtime automatically creates an ObjectResult
that wraps the object. Der Client empfängt das formatierte serialisierte Objekt.The client gets the formatted serialized object. Wenn das zurückgegebene Objekt null
ist, wird eine 204 No Content
-Antwort zurückgegeben.If the object being returned is null
, a 204 No Content
response is returned.
Zurückgeben eines Objekttyps:Returning an object type:
// GET api/authors/RickAndMSFT
[HttpGet("{alias}")]
public Author Get(string alias)
{
return _authors.GetByAlias(alias);
}
Im oben stehenden Code gibt die Anforderung eines gültigen Autoralias eine 200 OK
-Antwort mit den Daten des Autors zurück.In the preceding code, a request for a valid author alias returns a 200 OK
response with the author's data. Die Anforderung eines ungültigen Alias gibt eine 204 No Content
-Antwort zurück.A request for an invalid alias returns a 204 No Content
response.
Der Accept-HeaderThe Accept header
Eine Aushandlung des Inhalts findet statt, wenn in der Anforderung ein Accept
-Header angezeigt wird.Content negotiation takes place when an Accept
header appears in the request. Wenn eine Anforderung einen Accept-Header enthält, führt ASP.NET Core Folgendes aus:When a request contains an accept header, ASP.NET Core:
- Die Medientypen im Accept-Header werden in der bevorzugten Reihenfolge aufgelistet.Enumerates the media types in the accept header in preference order.
- Es wird versucht, einen Formatierer zu finden, der eine Antwort in einem der angegebenen Formate erzeugen kann.Tries to find a formatter that can produce a response in one of the formats specified.
Wenn kein Formatierer gefunden wird, der die Clientanforderung erfüllen kann, führt ASP.NET Core Folgendes aus:If no formatter is found that can satisfy the client's request, ASP.NET Core:
- Es wird
406 Not Acceptable
zurückgegeben, wenn MvcOptions festgelegt wurde, oderReturns406 Not Acceptable
if MvcOptions has been set, or - - Es wird versucht, den ersten Formatierer zu finden, der eine Antwort erzeugen kann.Tries to find the first formatter that can produce a response.
Wenn kein Formatierer für das angeforderte Format konfiguriert wurde, wird der erste Formatierer verwendet, der das Objekt formatieren kann.If no formatter is configured for the requested format, the first formatter that can format the object is used. Wenn in der Anforderung kein Accept
-Header vorhanden ist, gilt Folgendes:If no Accept
header appears in the request:
- Der erste Formatierer, der das Objekt verarbeiten kann, wird zum Serialisieren der Antwort verwendet.The first formatter that can handle the object is used to serialize the response.
- Es findet keine Aushandlung statt.There isn't any negotiation taking place. Der Server bestimmt, welches Format zurückgegeben werden soll.The server is determining what format to return.
Enthält der Accept-Header */*
, wird der Header ignoriert, es sei denn, RespectBrowserAcceptHeader
ist in MvcOptions auf TRUE festgelegt.If the Accept header contains */*
, the Header is ignored unless RespectBrowserAcceptHeader
is set to true on MvcOptions.
Browser und InhaltsaushandlungBrowsers and content negotiation
Im Gegensatz zu typischen API-Clients, stellen Webbrowser Accept
-Header bereit.Unlike typical API clients, web browsers supply Accept
headers. Webbrowser geben viele Formate an, einschließlich Platzhaltern.Web browser specify many formats, including wildcards. Wenn das Framework erkennt, dass eine Anforderung von einem Browser stammt, wird standardmäßig Folgendes ausgeführt:By default, when the framework detects that the request is coming from a browser:
- Der
Accept
-Header wird ignoriert.TheAccept
header is ignored. - Der Inhalt wird im JSON-Format zurückgegeben, sofern nicht anders konfiguriert.The content is returned in JSON, unless otherwise configured.
Dies sorgt bei der Verwendung von APIs für ein konsistenteres browserübergreifendes Benutzererlebnis.This provides a more consistent experience across browsers when consuming APIs.
Um eine App so zu konfigurieren, dass Accept-Header in Browsern berücksichtigt werden, legen Sie RespectBrowserAcceptHeader auf true
fest:To configure an app to honor browser accept headers, set RespectBrowserAcceptHeader to true
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Konfigurieren von FormatierernConfigure formatters
Apps, die zusätzliche Formate unterstützen müssen, können die geeigneten NuGet-Pakete hinzufügen und die Unterstützung konfigurieren.Apps that need to support additional formats can add the appropriate NuGet packages and configure support. Es gibt unterschiedliche Formatierungsprogramme für Ein- und für Ausgaben.There are separate formatters for input and output. Eingabeformatierer werden von der Modellbindung verwendet.Input formatters are used by Model Binding. Ausgabeformatierer werden zum Formatieren von Antworten verwendet.Output formatters are used to format responses. Informationen zum Erstellen eines benutzerdefinierten Formatierers finden Sie unter Benutzerdefinierte Formatierer.For information on creating a custom formatter, see Custom Formatters.
Hinzufügen von Unterstützung für das XML-FormatAdd XML format support
XML-Formatierer, die mithilfe von XmlSerializer implementiert wurden, werden durch Aufruf von AddXmlSerializerFormatters konfiguriert:XML formatters implemented using XmlSerializer are configured by calling AddXmlSerializerFormatters:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddXmlSerializerFormatters();
}
Der oben stehende Code serialisiert Ergebnisse mithilfe von XmlSerializer
.The preceding code serializes results using XmlSerializer
.
Bei Verwendung dieses Codes geben Controllermethoden das geeignete Format basierend auf dem Accept
-Header der Anforderung zurück.When using the preceding code, controller methods return the appropriate format based on the request's Accept
header.
Konfigurieren von System.Text.Json-basierten FormatierernConfigure System.Text.Json-based formatters
Funktionen für die System.Text.Json
-basierten Formatierer können mithilfe von Microsoft.AspNetCore.Mvc.JsonOptions.SerializerOptions
konfiguriert werden.Features for the System.Text.Json
-based formatters can be configured using Microsoft.AspNetCore.Mvc.JsonOptions.SerializerOptions
.
services.AddControllers().AddJsonOptions(options =>
{
// Use the default property (Pascal) casing.
options.JsonSerializerOptions.PropertyNamingPolicy = null;
// Configure a custom converter.
options.JsonSerializerOptions.Converters.Add(new MyCustomJsonConverter());
});
Optionen zur Ausgabeserialisierung können aktionsweise mithilfe von JsonResult
konfiguriert werden.Output serialization options, on a per-action basis, can be configured using JsonResult
. Zum Beispiel:For example:
public IActionResult Get()
{
return Json(model, new JsonSerializerOptions
{
WriteIndented = true,
});
}
Hinzufügen von Newtonsoft.Json-basierter Unterstützung für das JSON-FormatAdd Newtonsoft.Json-based JSON format support
Vor ASP.NET Core 3.0 wurden standardmäßig die JSON-Formatierer verwendet, die mithilfe des Newtonsoft.Json
-Pakets implementiert wurden.Prior to ASP.NET Core 3.0, the default used JSON formatters implemented using the Newtonsoft.Json
package. In ASP.NET Core 3.0 oder höher basieren die Standardformatierer für JSON auf System.Text.Json
.In ASP.NET Core 3.0 or later, the default JSON formatters are based on System.Text.Json
. Unterstützung für Newtonsoft.Json
basierte Formatierer und Features ist verfügbar, indem Microsoft.AspNetCore.Mvc.NewtonsoftJson
Sie das nuget-Paket installieren und in konfigurieren Startup.ConfigureServices
.Support for Newtonsoft.Json
based formatters and features is available by installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson
NuGet package and configuring it in Startup.ConfigureServices
.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
Im vorangehenden Code werden mit dem-Befehl AddNewtonsoftJson
die folgenden Features für Web-API, MVC und Pages konfiguriert, die verwendet werden können Razor Newtonsoft.Json
:In the preceding code, the call to AddNewtonsoftJson
configures the following Web API, MVC, and Razor Pages features to use Newtonsoft.Json
:
- Eingabe-und Ausgabe Formatierer, die JSON lesen und schreibenInput and output formatters that read and write JSON
- JsonResult
- JSON PatchJSON Patch
- IJsonHelper
- TempDataTempData
Einige Features funktionieren mit System.Text.Json
-basierten Formatierern möglicherweise nicht gut und erfordern einen Verweis auf die Newtonsoft.Json
-basierten Formatierer.Some features may not work well with System.Text.Json
-based formatters and require a reference to the Newtonsoft.Json
-based formatters. Verwenden Sie weiterhin Newtonsoft.Json
-basierte Formatierer, wenn für die App Folgendes gilt:Continue using the Newtonsoft.Json
-based formatters if the app:
- Sie verwendet
Newtonsoft.Json
-Attribute.UsesNewtonsoft.Json
attributes. Zum Beispiel:[JsonProperty]
oder[JsonIgnore]
.For example,[JsonProperty]
or[JsonIgnore]
. - Sie passt die Serialisierungseinstellungen an.Customizes the serialization settings.
- Sie nutzt Features, die von
Newtonsoft.Json
bereitgestellt werden.Relies on features thatNewtonsoft.Json
provides. Microsoft.AspNetCore.Mvc.JsonResult.SerializerSettings
konfiguriert.ConfiguresMicrosoft.AspNetCore.Mvc.JsonResult.SerializerSettings
. Vor ASP.NET Core 3.0 akzeptiertJsonResult.SerializerSettings
eine Instanz vonJsonSerializerSettings
, die fürNewtonsoft.Json
spezifisch ist.Prior to ASP.NET Core 3.0,JsonResult.SerializerSettings
accepts an instance ofJsonSerializerSettings
that is specific toNewtonsoft.Json
.- die OpenAPI-Dokumentation generiert.Generates OpenAPI documentation.
Funktionen für die Newtonsoft.Json
-basierten Formatierer können mithilfe von Microsoft.AspNetCore.Mvc.MvcNewtonsoftJsonOptions.SerializerSettings
konfiguriert werden:Features for the Newtonsoft.Json
-based formatters can be configured using Microsoft.AspNetCore.Mvc.MvcNewtonsoftJsonOptions.SerializerSettings
:
services.AddControllers().AddNewtonsoftJson(options =>
{
// Use the default property (Pascal) casing
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
// Configure a custom converter
options.SerializerSettings.Converters.Add(new MyCustomJsonConverter());
});
Optionen zur Ausgabeserialisierung können aktionsweise mithilfe von JsonResult
konfiguriert werden.Output serialization options, on a per-action basis, can be configured using JsonResult
. Zum Beispiel:For example:
public IActionResult Get()
{
return Json(model, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
});
}
Hinzufügen von Unterstützung für das XML-FormatAdd XML format support
Die XML-Formatierung erfordert das NuGet-Paket Microsoft.AspNetCore.Mvc.Formatters.Xml.XML formatting requires the Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet package.
XML-Formatierer, die mithilfe von XmlSerializer implementiert wurden, werden durch Aufruf von AddXmlSerializerFormatters konfiguriert:XML formatters implemented using XmlSerializer are configured by calling AddXmlSerializerFormatters:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddXmlSerializerFormatters();
}
Der oben stehende Code serialisiert Ergebnisse mithilfe von XmlSerializer
.The preceding code serializes results using XmlSerializer
.
Bei Verwendung dieses Codes sollten Controllermethoden das geeignete Format basierend auf dem Accept
-Header der Anforderung zurückgeben.When using the preceding code, controller methods should return the appropriate format based on the request's Accept
header.
Angeben eines FormatsSpecify a format
Um die Antwortformate einzuschränken, wenden Sie den [Produces]
Filter an.To restrict the response formats, apply the [Produces]
filter. Wie die Filtersmeisten Filter [Produces]
können auch auf Aktion, Controller oder globaler Bereich angewendet werden:Like most Filters, [Produces]
can be applied at the action, controller, or global scope:
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class WeatherForecastController : ControllerBase
{
Der vorangehende [Produces]
Filter:The preceding [Produces]
filter:
- Er erzwingt die Rückgabe von JSON-formatierten Antworten von allen Aktionen im Controller.Forces all actions within the controller to return JSON-formatted responses.
- Wenn andere Formatierer konfiguriert sind und der Client ein anderes Format angibt, wird JSON zurückgegeben.If other formatters are configured and the client specifies a different format, JSON is returned.
Weitere Informationen finden Sie unter Filter.For more information, see Filters.
Formatierer für besondere FälleSpecial case formatters
Einige besondere Fälle werden mithilfe von integrierten Formatierungsprogrammen implementiert.Some special cases are implemented using built-in formatters. Standardmäßig werden string
-Rückgabetypen als text/plain formatiert (bzw. als text/html , wenn sie über den Accept
-Header angefordert werden).By default, string
return types are formatted as text/plain ( text/html if requested via the Accept
header). Dieses Verhalten kann durch Entfernen von StringOutputFormatter gelöscht werden.This behavior can be deleted by removing the StringOutputFormatter. Formatierer werden in der ConfigureServices
-Methode entfernt.Formatters are removed in the ConfigureServices
method. Aktionen mit einem Modellobjekt-Rückgabetyp geben null
zurück, wenn der Rückgabewert 204 No Content
lautet.Actions that have a model object return type return 204 No Content
when returning null
. Dieses Verhalten kann durch Entfernen von HttpNoContentOutputFormatter gelöscht werden.This behavior can be deleted by removing the HttpNoContentOutputFormatter. Der folgende Code entfernt StringOutputFormatter
und HttpNoContentOutputFormatter
.The following code removes the StringOutputFormatter
and HttpNoContentOutputFormatter
.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
{
// requires using Microsoft.AspNetCore.Mvc.Formatters;
options.OutputFormatters.RemoveType<StringOutputFormatter>();
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
// requires using Microsoft.AspNetCore.Mvc.Formatters;
options.OutputFormatters.RemoveType<StringOutputFormatter>();
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Ohne den StringOutputFormatter
formatiert der integrierte JSON-Formatierer string
-Rückgabetypen.Without the StringOutputFormatter
, the built-in JSON formatter formats string
return types. Wenn der integrierte JSON-Formatierer entfernt wird und ein XML-Formatierer verfügbar ist, formatiert der XML-Formatierer string
-Rückgabetypen.If the built-in JSON formatter is removed and an XML formatter is available, the XML formatter formats string
return types. Andernfalls geben string
-Rückgabetypen 406 Not Acceptable
zurück.Otherwise, string
return types return 406 Not Acceptable
.
Ohne HttpNoContentOutputFormatter
werden NULL-Objekte mithilfe des konfigurierten Formatierungsprogramms formatiert.Without the HttpNoContentOutputFormatter
, null objects are formatted using the configured formatter. Zum Beispiel:For example:
- Der JSON-Formatierer gibt eine Antwort mit dem Text
null
zurück.The JSON formatter returns a response with a body ofnull
. - Der XML-Formatierer gibt ein leeres XML-Element mit festgelegtem Attribut
xsi:nil="true"
zurück.The XML formatter returns an empty XML element with the attributexsi:nil="true"
set.
Zuordnung des Antwortformats durch URLsResponse format URL mappings
Clients können in der URL ein bestimmtes Format anfordern, beispielsweise folgendermaßen:Clients can request a particular format as part of the URL, for example:
- In der Abfragezeichenfolge oder als Teil des Pfads.In the query string or part of the path.
- Durch Verwendung einer formatspezifischen Dateierweiterung wie „.xml“ oder „.json“.By using a format-specific file extension such as .xml or .json.
Die Zuordnung des Anforderungspfads sollte in der Route angegeben werden, die die API verwendet.The mapping from request path should be specified in the route the API is using. Zum Beispiel:For example:
[Route("api/[controller]")]
[ApiController]
[FormatFilter]
public class ProductsController : ControllerBase
{
[HttpGet("{id}.{format?}")]
public Product Get(int id)
{
Mit der oben genannten Route kann das angeforderte Format als optionale Dateierweiterung angegeben werden.The preceding route allows the requested format to be specified as an optional file extension. Das [FormatFilter]
-Attribut überprüft das vorhanden sein des Format Werts im RouteData
und ordnet das Antwortformat dem entsprechenden Formatierer zu, wenn die Antwort erstellt wird.The [FormatFilter]
attribute checks for the existence of the format value in the RouteData
and maps the response format to the appropriate formatter when the response is created.
RouteRoute | FormatierungsprogrammFormatter |
---|---|
/api/products/5 |
Standard-AusgabeformatierungsprogrammThe default output formatter |
/api/products/5.json |
JSON-Formatierungsprogramm (falls konfiguriert)The JSON formatter (if configured) |
/api/products/5.xml |
XML-Formatierungsprogramm (falls konfiguriert)The XML formatter (if configured) |