我的网络API中有一个操作正在返回HttpResponseMessage
:
public async Task<HttpResponseMessage> Create([FromBody] AType payload)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
await Task.Delay(1);
var t = new T { Id = 0, Name = payload.tName, Guid = Guid.NewGuid() };
var response = new MyResponse { T = t };
var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent(typeof(MyResponse), response, new JsonMediaTypeFormatter { SerializerSettings = { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore } }) };
return result;
}
现在,我的问题是,如果发出请求且请求的Content-Type
为application/xml
,我应该使用xml formatter
来设置回复的正文。
有没有办法使用泛型类,让框架根据请求的内容类型决定在运行时使用哪种格式化程序?
答案 0 :(得分:1)
在请求中使用CreateResponse
扩展方法,它将允许基于相关请求进行内容协商。如果要根据请求的内容类型强制内容类型,请从请求中获取内容类型并将其包含在create response overloads中。
public class MyApitController : ApiController {
[HttpPost]
public async Task<HttpResponseMessage> Create([FromBody] AType payload) {
if (payload == null) {
throw new ArgumentNullException(nameof(payload));
}
await Task.Delay(1);
var t = new T { Id = 0, Name = payload.tName, Guid = Guid.NewGuid() };
var response = new MyResponse { T = t };
var contentType = Request.Content.Headers.ContentType;
var result = Request.CreateResponse(HttpStatusCode.OK, response, contentType);
return result;
}
}
理想情况下,返回的类型应基于请求表明它要接受的内容。该框架确实允许该主题具有灵活性。
选中此处以获取更多信息Content Negotiation in ASP.NET Web API
答案 1 :(得分:0)
更简单的方法是使用Web API 2 ApiController中的方便方法。
[HttpPost]
public async Task<IHttpActionResult> Create([FromBody] AType payload)
{
if (payload == null)
{
return BadRequest("Must provide payload");
}
await Task.Delay(1);
var t = new T { Id = 0, Name = payload.tName, Guid = Guid.NewGuid() };
var response = new MyResponse { T = t };
return Ok(response);
}