Why won't my ASP.Net Core Web API Controller return XML?

后端 未结 8 2261
自闭症患者
自闭症患者 2020-12-14 08:28

I have the following simple Web API controller:

    // GET: api/customers
    [HttpGet]
    public async Task Get()
        {
        var         


        
8条回答
  •  甜味超标
    2020-12-14 09:02

    For Asp.Net Core 2.x you basically need these 3 things in order to return an XML response:

    Startup.cs:

    services
        .AddMvcCore(options => options.OutputFormatters.Add(new XmlSerializerOutputFormatter())
    

    CustomerController.cs:

    using Microsoft.AspNetCore.Mvc;
    
    namespace WebApplication
    {
        [Route("api/[controller]")]
        public class CustomerController : ControllerBase
        {
            [HttpGet]
            public IActionResult Get()
            {
                var customer = new CustomerDto {Id = 1, Name = "John", Age = 45};
                return Ok(customer);
            }
        }
    }
    

    CustomerDto.cs:

    namespace WebApplication
    {
        public class CustomerDto
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
    

    And then upon adding the Accept "application/xml" header to the request an XML formatted result will be returned.

    A very important note that I had to find out for myself is if your model does not have an implicit of explicit parameterless constructor then the response will be written as a json. Given the following example

    namespace WebApplication
    {
        public class CustomerDto
        {
            public CustomerDto(int id, string name, int age)
            {
                Id = id;
                Name = name;
                Age = age;
            }
    
             public int Id { get; }
             public string Name { get; }
             public int Age { get; }
        }
    }
    

    It would return json. To this model you should add

    public CustomerDto()
    {
    }
    

    And that would again return XML.

提交回复
热议问题