我在我的Web 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
来放置响应的主体。
是否有一种方法可以使用通用类,并让框架根据请求的内容类型在运行时决定使用哪个格式化程序?
Request.CreateResponse(HttpStatusCode.OK, response, Request.Content.Headers.ContentType);
- Nkosi