如何 return xml 或 json 与 ASP.NET web mvc 6 取决于接受 Header
How to return xml or json with ASP.NET web mvc 6 depending on Accept Header
我已经使用 ASP.NET mvc 6 实现了一个网络 api 控制器,我想 return 控制器的结果为 json 或 xml,取决于客户的接受header。例如,如果客户端发送带有 "Accept: application/xml" 的 GET 请求,那么 returned 响应应该是 xml。如果 header 是 "Accept: application/json",那么它应该是 json。目前控制器总是 returns json。有没有办法配置这个?注意:这个问题确实是 的重复。但是那里提供的解决方案并没有解决我的问题。下面接受的答案对我有用。
下面给出了控制器,它是由 ASP.NET 5 web api 模板提供的:
[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)
{
}
}
感谢您的帮助!
我帮你做了调查,你可以自己继续:
需要:
"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"
启动:
services.Configure<MvcOptions>(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});
从 here
继续
我已经使用 ASP.NET mvc 6 实现了一个网络 api 控制器,我想 return 控制器的结果为 json 或 xml,取决于客户的接受header。例如,如果客户端发送带有 "Accept: application/xml" 的 GET 请求,那么 returned 响应应该是 xml。如果 header 是 "Accept: application/json",那么它应该是 json。目前控制器总是 returns json。有没有办法配置这个?注意:这个问题确实是
下面给出了控制器,它是由 ASP.NET 5 web api 模板提供的:
[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)
{
}
}
感谢您的帮助!
我帮你做了调查,你可以自己继续:
需要:
"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"
启动:
services.Configure<MvcOptions>(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});
从 here
继续