Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml Requests do not work

I cannot get a bare bones Asp.Net Core Web Api project to work using Xml instead of Json. Please help!

I have created a new project and the only adjustments to the default configuration were to add the Xml formatters...

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc(config =>
    {
        config.InputFormatters.Add(new XmlSerializerInputFormatter());
        config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });
}

My Controller also contains simple Get and Post methods:

[Route("api")]
public class MessageController : Controller
{
    [HttpPost]
    public void Post([FromBody] Message message)
    {

    }

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new Message
        {
            TestProperty = "Test value"
        });
    }
}

When I try calling the POST method with Content-Type: application/xml, the API returns 415 Unsupported Media Type. I have tried adding the Consumes("application/xml") attribute to the controller and still it does not work.

The GET works and returns JSON. However, if I add the Produces("application/xml") attribute to the controller, the GET returns 406 Not Acceptable, even if I provide the Accepts: application/xml header.

For some reason, the API is completely rejecting anything related to xml even though the input and output formatters were added as I have seen in the very few examples I could find.

What am I missing?

like image 585
frangelico87 Avatar asked Aug 29 '16 06:08

frangelico87


3 Answers

I have following thing in my startup.cs and it works well with XML and JSON both. Here I only stick with XML. Note : ( I have consider my own class for sample)

  1. Startup.cs

    public void ConfigureServices(IServiceCollection services)
        { 
            services.AddMvcCore()
                    .AddJsonFormatters().AddXmlSerializerFormatters();
        }
    
  2. My HttpClient Code ( You might have missed Content Type setting that I have done in StringCotent)

    • Two header is important : Accept and Content-Type. Accept help in content negotiation and Content-Type is a way client tell server what type content client is posting.

       HttpClient client = new HttpClient();
       client.BaseAddress = new Uri( @"http://localhost:5000");
       client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
      
      
       HttpContent content = new StringContent(@"<Product>
      <Id>122</Id>
      <Name>Computer112</Name></Product>",System.Text.Encoding.UTF8 , "application/xml");  // This is important.
      
      var result = client.PostAsync("/api/Products", content).Result;
      
like image 175
dotnetstep Avatar answered Oct 12 '22 13:10

dotnetstep


In ASP.Net Core 2.0 you can accept both XML and Json request almost out of the box.

In Startup class in ConfigureServices method, you should have:

services
    .AddMvc()
    .AddXmlSerializerFormatters();

And controller that accepts complex object looks like this:

[Route("api/Documents")]
public class DocumentsController : Controller
{
    [Route("SendDocument")]
    [HttpPost]
    public ActionResult SendDocument([FromBody]DocumentDto document)
    {
        return Ok();
    }
}

This is an XML to send:

<document>
    <id>123456</id>
<content>This is document that I posted...</content>
<author>Michał Białecki</author>
<links>
    <link>2345</link>
    <link>5678</link>
</links>

{
    id: "1234",
    content: "This is document that I posted...",
    author: "Michał Białecki",
    links: {
        link: ["1234", "5678"]
    }
}

And that’s it! It just works.

.net core debugging

Request with the same document either in XML or Json to api/documents/SendDocument endpoint is handled by one method. Only remember about correct Content-Type header in your request.

You can read the whole post at my blog: http://www.michalbialecki.com/2018/04/25/accept-xml-request-in-asp-net-mvc-controller/

like image 36
Mik Avatar answered Oct 12 '22 13:10

Mik


For ASP.NET Core 2.2 use nuget package Microsoft.AspNetCore.Mvc.Formatters.Xml or Microsoft.AspNetCore.App and add this in Startup.cs

      services.AddMvc()
       .AddXmlSerializerFormatters()
       .AddXmlDataContractSerializerFormatters();

Don't forget to use headers Accept application/xml to get response as xml and Content-Type application/xml for request with xml body.

Check example here http://www.devcode4.com/article/asp-net-core-xml-request-response

like image 2
Petofi Avatar answered Oct 12 '22 14:10

Petofi