3

I have implemented a web api controller using ASP.NET mvc 6 and I would like to return the result of the controller as json or xml, depending on the client's Accept header. For example, if the client sends a GET request with "Accept: application/xml", then the returned response should be xml. If the header is "Accept: application/json", then it should be json. At the moment the controller always returns json. Is there a way of configuring this? Note: this question is indeed a duplicate of How to return XML from an ASP.NET 5 MVC 6 controller action. However the solution provided there did not solve my problem. The accepted answer below worked for me.

The controller is given below and is the one provided by the ASP.NET 5 web api template:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id:int}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

Thanks for your help!

Community
  • 1
  • 1
BigONotation
  • 4,406
  • 5
  • 43
  • 72
  • [here](http://stackoverflow.com/questions/32354449/how-to-return-xml-from-an-asp-net-5-mvc-6-controller-action) you may find hints...and this could be a duplicate – vinjenzo Jan 31 '16 at 19:57
  • @Prescott yes this might be a duplicate. However I tried to follow the steps provided in your link. This does not seem to work when you are targeting both core and the regular .NET 4.6 framework. I need a solution for both platforms – BigONotation Jan 31 '16 at 20:11
  • I am getting the following error CS0012 The type 'MvcOptions' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNet.Mvc.Core, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null'. I tried to add "Microsoft.AspNet.Mvc.Core" : "6.0.0-rc1-final" to my project.json but still getting this error. Which package defines MvcOptions? – BigONotation Jan 31 '16 at 20:51

1 Answers1

6

I did the research for you, you may continue alone:

needed:

"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Core": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final"

startup:

 services.Configure<MvcOptions>(options =>
 {
   options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
 });

go on from here

another

and antoher

Community
  • 1
  • 1
vinjenzo
  • 1,490
  • 13
  • 13