Search code examples
xmlrestasp.net-core-2.2inputformatter

ASP.NET Core 2.2, input formatters for XML


I'm using asp.net core 2.2 and trying to allow additional content-type value for XML. So I configured in Startup.cs like this.

services.AddMvc(options =>
        {
            options.ReturnHttpNotAcceptable = true;
            options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 

In fact, I ended up getting 415 Unsupported Media Type status in postman. Has anyone succeeded with adding XML content-type value?

AuthorsController.cs:

    [HttpPost]
    public ActionResult CreateAuthor([FromBody] AuthorForCreationDto author)
    {
        ...
    }

enter image description here

enter image description here


Solution

  • You need to set RespectBrowserAcceptHeader to true to allow content negotiation.

    // Add XML Content Negotiation
    config.RespectBrowserAcceptHeader = true;
    
    
    services.AddMvc(options => {
        //Enable this to allow content negotiation.
        options.RespectBrowserAcceptHeader = true;
    
        options.ReturnHttpNotAcceptable = true;
        options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
        options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);