A legacy partner calls an ASP.NET Core 10 controller API with XML only; how do you support it, and when does the partner get 406 or 415?
answer
- formatters are an MVC feature
- AddXmlSerializerFormatters, no extra package
- [Consumes] answers 415 on a mismatch
- [Produces] narrows the output types
- ReturnHttpNotAcceptable defaults to false
basics
~20 sCall AddXmlSerializerFormatters on AddControllers, then mark the partner's actions [Consumes("application/xml")] and [Produces("application/xml")]. A mismatched Content-Type gets 415; an unsatisfiable Accept gets 406 only when MvcOptions.ReturnHttpNotAcceptable is true, otherwise the response falls back to a default format.
solid answer
~40 sXML support is an MVC formatter feature: `AddControllers().AddXmlSerializerFormatters()` (or `AddXmlDataContractSerializerFormatters()`) appends XML input and output formatters, which ship in the shared framework. They are added after the JSON formatter, so JSON stays the answer when there is no `Accept` header or it is `*/*`. For the partner's controller, `[Consumes("application/xml")]` rejects any other non-empty `Content-Type` with 415, and `[Produces("application/xml")]` restricts output to XML. If the partner then sends `Accept: application/json`, MVC writes XML anyway unless `MvcOptions.ReturnHttpNotAcceptable` is `true`, in which case it answers 406. Without `[Consumes]`, a body whose content type no input formatter reads also ends in 415, through the `UnsupportedContentTypeFilter`. Minimal API endpoints have no formatters, so they write JSON only.
code
http · 8 linesPOST /partner/labels HTTP/1.1
Host: api.example.test
Content-Type: application/xml
Accept: application/json
<CreateLabelRequest><TrackingNumber>1Z999</TrackingNumber><WeightGrams>1200</WeightGrams></CreateLabelRequest>
HTTP/1.1 406 Not Acceptablego deeper
Recall that AddXmlSerializerFormatters enables XML for controllers and that [Consumes] and [Produces] declare request and response media types.
Explain formatter order, why JSON stays the default, and what [Consumes] and [Produces] each do at runtime.
Predict the exact status for each header combination, decide whether ReturnHttpNotAcceptable is safe for your clients, and keep error bodies in the partner's format.
Decide whether a legacy format belongs in the main API or behind a dedicated adapter, weighing negotiation complexity against partner commitments.
## Formatters are the mechanism In ASP.NET Core MVC, request bodies are read by **input formatters** and responses are written by **output formatters**, both lists on `MvcOptions`. By default the input list holds `SystemTextJsonInputFormatter`, and the output list holds `HttpNoContentOutputFormatter`, `StringOutputFormatter`, `StreamOutputFormatter` and `SystemTextJsonOutputFormatter`. Minimal APIs do not use this machinery at all: `Results`, `TypedResults` and returned objects are written as JSON through the HTTP JSON helpers. An XML-only partner is therefore a controller job, unless you write a custom `IResult`. ## Adding XML ```csharp builder.Services.AddControllers(o => o.ReturnHttpNotAcceptable = true) .AddXmlSerializerFormatters(); ``` - `AddXmlSerializerFormatters` uses `XmlSerializer`; `AddXmlDataContractSerializerFormatters` uses `DataContractSerializer`. Pick the one whose XML shape matches the partner's schema. - The formatters live in `Microsoft.AspNetCore.Mvc.Formatters.Xml`, which is part of the ASP.NET Core shared framework, so no package reference is needed. - They are **appended**, so the JSON output formatter still comes first. A client with no `Accept` header, or one sending `*/*` (ignored while `RespectBrowserAcceptHeader` is `false`), still gets JSON. - The setup also maps the format key `xml`, so `[FormatFilter]` with a `{format}` route value can select XML by URL. - `XmlSerializer` needs a public parameterless constructor; plain DTO classes are a safer contract than positional records. ## [Consumes] and [Produces] on the partner's controller ```csharp [ApiController] [Route("partner/labels")] [Consumes("application/xml")] [Produces("application/xml")] public class PartnerLabelsController : ControllerBase { /* ... */ } ``` | Attribute | Kind | What it does | |---|---|---| | `[Consumes]` | resource filter and action constraint | rejects a request whose non-empty `Content-Type` is not covered with `UnsupportedMediaTypeResult` (415); can also choose between two actions on the same route by content type | | `[Produces]` | result filter | sets `ObjectResult.ContentTypes`, so only formatters for those types are considered; also feeds API description metadata | Two details matter. A request **without** a `Content-Type` is not rejected by `[Consumes]`; the attribute deliberately lets GET requests through. And `[Produces]` affects only object results; a `FileResult` or `ContentResult` sets its own type. ## When the partner sees 406 or 415 1. **415, declared:** the partner posts `Content-Type: application/json` to an action under `[Consumes("application/xml")]`. 2. **415, undeclared:** with no `[Consumes]`, the body model binder finds no input formatter for the content type, records an `UnsupportedContentTypeException` in `ModelState`, and the global `UnsupportedContentTypeFilter` turns it into a 415. 3. **406:** output selection finds no formatter that satisfies the `Accept` header together with `[Produces]`, **and** `ReturnHttpNotAcceptable` is `true`. 4. **No error at all:** the same mismatch with `ReturnHttpNotAcceptable = false` (the default) falls back to a formatter that can write the result, here XML. ## XmlSerializer or DataContractSerializer | | `AddXmlSerializerFormatters` | `AddXmlDataContractSerializerFormatters` | |---|---|---| | Serializer | `XmlSerializer` | `DataContractSerializer` | | Shape control | `[XmlElement]`, `[XmlAttribute]`, `[XmlRoot]` | `[DataContract]`, `[DataMember]` | | Typical fit | an existing XSD with attributes and specific element names | a contract shared with older WCF-style services | `DataContractSerializer` writes members as elements, so a partner schema that uses XML attributes points to `XmlSerializer`; the schema usually decides the choice. ## Checking it by hand Send the partner's exact headers with `curl -H "Accept: application/xml" -H "Content-Type: application/xml"` and then vary one header at a time. Each variation should produce the status the table above predicts; any surprise usually means a `[Produces]` or `[Consumes]` at the controller level that the action did not expect. ## Operating it - Turn on `ReturnHttpNotAcceptable` only when clients send precise `Accept` headers; otherwise a client sending `Accept: text/html` suddenly gets 406 instead of usable JSON. - Error bodies follow negotiation too: the XML formatters wrap `ProblemDetails` and `ValidationProblemDetails`, so the partner gets validation errors as XML. - Log the `Accept` and `Content-Type` headers on 406 and 415 responses; the formatter selector also logs which formatter it chose at debug level.
- Why does a browser hitting the partner endpoint get JSON instead of XML, even with XML formatters registered and no [Produces]?Browsers send an `Accept` header containing `*/*`. While `MvcOptions.RespectBrowserAcceptHeader` is `false` (the default), MVC treats such a header as absent and uses the first output formatter that can write the result, and the JSON formatter is registered before the appended XML formatters.
- How can [Consumes] route one URL to two different actions?`[Consumes]` is also an action constraint. Two POST actions on `partner/labels`, one with `[Consumes("application/xml")]` and one with `[Consumes("application/json")]`, are selected by the request's `Content-Type`, so XML and JSON clients can share a URL while each action binds its own DTO.
- MVC returns 406 by default whenever the Accept header cannot be satisfied.
- XML formatters need a separate NuGet package before AddXmlSerializerFormatters works.
- Registering XML formatters makes XML the default response format for every client.
- [Consumes] also rejects requests that send no Content-Type at all.
- Minimal API endpoints negotiate XML once AddXmlSerializerFormatters is called.