0

I wanted to see if I can havew my API return "XML" so I changed the Accept Header to XML like this pic below : enter image description here

And I updated my code like this below. But still it returns JSON : Why?

builder.Services.AddControllers(options =>
{
    options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();

I was following a PluralSight course that was doing this and worked for him.

4
  • 2
    how does your controller looked like? Commented Jun 25, 2023 at 13:11
  • @BagusTesa oh you were right! my controller was still saying return new JaonResult !! LOL ... OK that fixed it. Thanks. Commented Jun 25, 2023 at 13:14
  • 1
    You can also annotate your controller with ` .AddXmlSerializerFormatters();` (in your services configuration) and Produces("application/xml")]: (annotate your controller): stackoverflow.com/a/59191378/421195 Commented Jun 27, 2023 at 1:03
  • 1
    If you want to support clients that can't / won't set the accept header, I'd recommend an explicit format parameter in the url [FormatFilter, Route(".../name.{format}")] Commented Jun 27, 2023 at 2:53

1 Answer 1

1

And I updated my code like this below. But still it returns JSON : Why?

According to your description and shared snippet I have tired to simulate your issue and its working as expected. In addition, I can switch between XML and Json response from the header value.

You can refer to following sample:

Demo Model:

public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }  

Demo Controller:

    [Route("api/[controller]")]
    [ApiController]
    public class CityXMLController : ControllerBase
    {
        public IActionResult GetCity()
        {
            var cityList = new List<City>()
            {
                new City { Id = 101, Name = "Alberta" },
                new City { Id = 102, Name = "Toronto" },
                new City { Id = 103, Name = "British Comlombia" },
            };
            return Ok(cityList);
        }
    }

Note: Please make sure you are using Ok as return type in order to handle dynamic request header both (XML and Json) because, specific return type would fail opposite response type as per header value.

Program.cs:

builder.Services.AddControllers(options =>
{
    options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();

Output:

enter image description here

enter image description here

Note: If you would like to know more details on Accept header configuration you could check our official document here.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.