Search code examples
xml-parsingxmlhttprequestasp.net-core-webapicontent-type

api cannot accept XML


I'm using .netCore 3.1 and this is my first time dealing with XML. I'm trying to read xml data, and parse them then save them to the db. I have a model named ExternalAppointment that I want to map data to. here's my controller :

    [HttpPost("xml")]
    public async Task<ActionResult<Appointment>> XMLContent([FromBody] ExternalAppointment xmldata)
    {
        //stuff.
    }

here's my startup.cs :

        services.Configure<RequestLocalizationOptions>(options =>
        {
            //some code
            services.AddMvc()
            .AddXmlSerializerFormatters();
            //rest of code
        }

here's the xml I'm passing in postman:

    <?xml version="1.0" encoding="UTF-8"?>
<event>
   <business_owner_id>1</business_owner_id>
   <business_owner_name>Doctor's lab</business_owner_name>
   <business_owner_phone_number>44556699887</business_owner_phone_number>
   <customer_email>[email protected]</customer_email>
   <customer_phone_number>1122336655</customer_phone_number>
   <date_and_time>16/12/2021 20:45:00</date_and_time>
   <location>21 jump street</location>
   <service_name>PCR</service_name>
</event>

and I can't seem to get through to the request, I keep getting 405 response. I tried adding [consumes("application/xml")] decorator before the controller but it did not help.

any ideas ?


Solution

  • Here is my demo with XElement,and it can work:

    Startup:

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

    ApiController:

     [Route("api/[controller]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        [HttpPost("xml")]
        public IActionResult XMLContent([FromBody] XElement xmldata)
        {
            return Ok();
            //stuff.
        }
    }
    

    postman(You need to make sure you use post request): enter image description here

    result: enter image description here