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

后端 未结 8 2136
自闭症患者
自闭症患者 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 08:51

    For asp.net core 2.x, you can configure OutputFormatter.

    you can try following code pieces in startup.cs class ConfigureServices method.

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc(action =>
         {
             action.ReturnHttpNotAcceptable = true;
             action.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
         });
    
         //...
    }
    

    For using XmlDataContractSerializerOutputFormatter references from Microsoft.AspNetCore.Mvc.Formatters package from nuget.

    now it should work for xml and json

    0 讨论(0)
  • 2020-12-14 08:52

    For MVC 1.1 you need to add the Package Microsoft.AspNetCore.Mvc.Formatters.Xml and edit your Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; })
            .AddXmlSerializerFormatters()
            .AddXmlDataContractSeria‌​lizerFormatters();
    }
    

    Now you can set the Accept Header:

    XML: application/xml

    JSON: application/json

    0 讨论(0)
  • 2020-12-14 08:59

    Xml formatters are part of a separate package: Microsoft.AspNetCore.Mvc.Formatters.Xml

    Add the above package and update your startup.cs like below:

    services
        .AddMvc()
        .AddXmlDataContractSerializerFormatters();
    

    OR

    services
        .AddMvc()
        .AddXmlSerializerFormatters();
    
    0 讨论(0)
  • 2020-12-14 08:59

    For Core 2.x versions, you have to do two things. First thing is you need to add following code inside the ConfigureServices method of Startup.cs file.

    services.AddMvc()
    .AddMvcOptions(o => o.OutputFormatters.Add(
        new XmlDataContractSerializerOutputFormatter())
    );
    

    And then add the Accept "application/xml" header to the request as below on Postman. Then XML formatted result will be returned.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 09:03

    The following solution worked for me nicely.

    At Startup.cs

    services.AddMvc()
           .AddXmlSerializerFormatters()
           .AddXmlDataContractSerializerFormatters();
    

    At YourController.cs

        [HttpGet]
        [Route("Get")]
        [Produces("application/xml")] // If you don't like to send Content-Type header
        public IActionResult Get()
        {
            try
            {                
                var user = _userManager.FindByNameAsync('user').Result;
                if (user != null)
                {
                    if (!_userManager.CheckPasswordAsync(user, 'password').Result)
                    {
                        return Unauthorized();
                    }
                    else
                    {
                        var result = _services.GetDataFromService(Convert.ToInt64(2), start_date, end_date);
                        return Ok(result);
                    }
                }
                else
                {
                    return Unauthorized();
                }
            }
            catch (Exception ex)
            {
                return Unauthorized();
            }
        }
    
    0 讨论(0)
提交回复
热议问题