8

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.

rahul
  • 232
  • 1
  • 5
  • 13

1 Answers1

15

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

mj1313
  • 7,930
  • 2
  • 12
  • 32
  • 1
    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 – rahul May 05 '20 at 09:57
  • 3
    Thanks for the answer, I noticed that it works even without [Consumes("application/xml")] attribute. – Ankit Sep 30 '20 at 02:19
  • 1
    Caution doesn't use services.AddControllers().AddXmlDataContractSerializerFormatters(), use only services.AddControllers().AddXmlSerializerFormatters() – golfalot Feb 18 '22 at 00:53