10

I have a .net core 3.1 web api. I have tried the following but it always turns up null when it hits it

[HttpPost]     
    public IActionResult ReturnXmlDocument(HttpRequestMessage request)
    {
        var doc = new XmlDocument();
        doc.Load(request.Content.ReadAsStreamAsync().Result);        
        return Ok(doc.DocumentElement.OuterXml.ToString());
    }

It doent even hits it during debugging also it shows a 415 error in fiddler.

1
  • I have tried passing content type and accept headers as XML to no avail Commented May 3, 2020 at 17:15

2 Answers 2

21

Asp.net core no longer uses HttpRequestMessage or HttpResponseMessage.

So, if you want to accept a xml format request, you should do the below steps:

1.Install the Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet package.

2.Call AddXmlSerializerFormatters In Startup.ConfigureServices.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddXmlSerializerFormatters(); 
    }

3.Apply the Consumes attribute to controller classes or action methods that should expect XML in the request body.

 [HttpPost]
    [Consumes("application/xml")]
    public IActionResult Post(Model model)
    {
        return Ok();
    }

For more details, you can refer to the offical document of Model binding

Sign up to request clarification or add additional context in comments.

3 Comments

Your solution works..thnaks....i want to know addtionally i do not want to declare a model OR when i want to save the input in string or in XMLDocument directly. will it be possible
Thanks for the answer, I noticed that it works even without [Consumes("application/xml")] attribute.
Caution doesn't use services.AddControllers().AddXmlDataContractSerializerFormatters(), use only services.AddControllers().AddXmlSerializerFormatters()
3

For newer versions of .NET Core

The previous answer from mj1313 was correct, but the "Microsoft.AspNetCore.Mvc.Formatters.Xml" library is now deprecated and no longer maintained.

I found a more simple and still valid solution for .NET Core MVC apis, just add this ".AddXmlDataContractSerializerFormatters()" method call to your Program.cs file:

public void ConfigureServices(IServiceCollection services)
{
     services.AddControllers().AddXmlDataContractSerializerFormatters();
}

Source: https://gavilan.blog/2020/01/22/asp-net-core-3-1-accept-and-content-type-adding-xml-support-to-a-web-api/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.