首先, 5 没有了 MVC 和 WebApi 的区分,都属于 5,从 Controller 的继承就可以看出,原来 WebApi 2ValuesController : ApiController
改成了ValuesController : Controller
,并且返回 HttpResponseMessage 也有些改变。
WebApi 2 中的示例代码:
[Route("values/{id}")]public async Task<HttpResponseMessage> Get(string id){var response = Request.CreateResponse(HttpStatusCode.OK);var accept = Request.Headers.Accept;var result = await _valuesService.Get(id);if (accept.Any(x => x.MediaType == "text/html")){response.Content = new StringContent(result, Encoding.UTF8, "text/html");}else{response.Content = new StringContent(result, Encoding.UTF8, "text/plain");}return response;}
5 WebApi 中的示例代码:
[Route("values/{id}")]public async Task Get(string id){var accept = Request.GetTypedHeaders().Accept;var result = await _valuesService.Get(id);var data = Encoding.UTF8.GetBytes(result);if (accept.Any(x => x.MediaType == "text/html")){Response.ContentType = "text/html";}else{Response.ContentType = "text/plain";}await Response.Body.WriteAsync(data, 0, data.Length);}
可以看到,改变还是很大的,主要是两方面:
没有了Request.CreateResponse
,获取 Accept 需要通过Request.GetTypedHeaders()
。没有返回值,而是直接通过数据流的方式写入到Response.Body
中。
参考资料:
Breaking changes list and migration guidance are neededHow to create a response message and add content string to it in 5 / MVC 6Where all types for http headers gone in 5?
如果觉得《ASP.NET 5 WebApi 返回 HttpResponseMessage》对你有帮助,请点赞、收藏,并留下你的观点哦!