Why is my ASP.NET Core Web API app not returning XML? It is always returning JSON. When I specify "[Produces("application/xml")]" attribute in my controller, it returns a 406 status code:
Here is my controller code:
using GlobalWarmingCenter.Data; using GlobalWarmingCenter.Models; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System.Threading.Tasks; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace GlobalWarmingCenter.Controllers { [Route("api/[controller]")] public class DimCustomerController : Controller { private readonly PointOfContact _pointOfContact; private readonly AdventureWorksDW2012Context _context; private readonly ILogger _logger; private readonly IAntiforgery _antiforgery; public DimCustomerController(AdventureWorksDW2012Context context, ILogger<DimCustomerController> logger, IOptions<PointOfContact> PointOfContact, IAntiforgery antiforgery) { _context = context; _logger = logger; _pointOfContact = PointOfContact.Value; _antiforgery = antiforgery; } [HttpGet] public IActionResult Get() { var tokens = _antiforgery.GetAndStoreTokens(HttpContext); return new ObjectResult(new { token = tokens.RequestToken, tokenName = tokens.HeaderName }); } // GET: /<controller>/ public IActionResult Index() { return View(); } [HttpPost("{maritalstatus}")] [ValidateAntiForgeryToken] [Produces("application/xml")] public async Task<IActionResult> Index( [Bind("MaritalStatus")] DimCustomer dimcustomer) { try { DimCustomer[] result = null; if (ModelState.IsValid) { var something = dimcustomer.MaritalStatus; result = await _context.DimCustomer.FromSql("usp_GetAllDimCustomer @p0", dimcustomer.MaritalStatus).ToArrayAsync(); } var tokens = _antiforgery.GetAndStoreTokens(HttpContext); // return new OkObjectResult(tokens); return Ok(result); } catch (DbUpdateException ex) { //Log the error (uncomment ex variable name and write a log. ModelState.AddModelError("", ex.Message); ModelState.AddModelError("", "Unable to save changes. " +"Try again, and if the problem persists, " +"contact me at " + _pointOfContact.EmailAddress + "."); return View(); } } } }
I added the XML serializer formatters to my Startup.cs file:
services.AddMvc().AddXmlSerializerFormatters();
When I remove the "[Produces("application/xml")]" attribute from my controller, it returns JSON. However, I put "Accept: application/xml" and "Content-Type: application/xml" in my headers, as you can see in the screenshot (link provided above).
Thanks!