1. 程式人生 > >asp.net core WebApi 返回 HttpResponseMessage

asp.net core WebApi 返回 HttpResponseMessage

ASP.NET 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;
}

ASP.NET Core 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 中。