rahul
rahul

Reputation: 294

How to pass xml input (request) to Web api on .net core 3.1

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.

Upvotes: 10

Views: 28109

Answers (2)

Diego Arias
Diego Arias

Reputation: 373

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/

Upvotes: 3

mj1313
mj1313

Reputation: 8459

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

Upvotes: 21

Related Questions