zoukankan      html  css  js  c++  java
  • 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 中。

     
     
  • 相关阅读:
    [转载] CSS模块化【封装继承多态】
    【转】jquery图片播放插件Fancybox使用方法
    指定打印宽度,左&右对其
    预测编码与帧间压缩方法
    字符串
    静态变量 static
    利用getchar, putchar复制文件
    排序
    printf 语句
    Ubuntu 宽带连接
  • 原文地址:https://www.cnblogs.com/webenh/p/11434725.html
Copyright © 2011-2022 走看看