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!

3
  • here you may find hints...and this could be a duplicate Commented Jan 31, 2016 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 Commented Jan 31, 2016 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? Commented Jan 31, 2016 at 20:51

1 Answer 1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.