zoukankan      html  css  js  c++  java
  • 能省则省:在ASP.NET Web API中通过HTTP Headers返回数据

    对于一些返回数据非常简单的 Web API,比如我们今天遇到的“返回指定用户的未读站内短消息数”,返回数据就是一个数字,如果通过 http response body 返回数据,显得有些奢侈。何不直接通过 http headers 返回呢?节能又环保。于是今天在 ASP.NET Web API 中实际试了一下,证明是可行的。

    在 Web API 服务端借助 HttpResponseMessage ,可以很轻松地实现,代码如下:

    public class MessagesController : ApiController
    {
        [Route("api/messages/user-{userId}/unread/count")]
        public async Task<HttpResponseMessage> GetUserUnreadMessageCount(int userId)
        {
            var unreadCount = 10;
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("X-RESULT-COUNT", unreadCount.ToString());
            return response;
        }
    }

    而调用客户端只需直接从 http headers 中读取数据,无需从 http response body 中读取(如果用 HttpClient 就省掉了 Content.ReadAsStringAsync 操作),从而节省了资源。代码如下:

    public class WebApiTest
    {
        [Fact]
        public async Task Get_User_Unread_Message_Count()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new System.Uri("www.cnblogs.com");
                var userId = 1;
                var response = await client.GetAsync($"/api/messages/user-{userId}/unread/count");
                if (response.IsSuccessStatusCode)
                {
                    var unreadCount = response.Headers.GetValues("X-RESULT-COUNT").FirstOrDefault();
                    Console.WriteLine(unreadCount);
                    Assert.Equal(10, int.Parse(unreadCount));
                }
                else
                {
                    Console.WriteLine(response.StatusCode);
                    Console.WriteLine(await response.Content.ReadAsStringAsync());
                }
            }
        }
    }

    【参考资料】

    Getting a count of returns seen by a RESTful request

    Paging in ASP.NET Web API: Using HTTP Headers

  • 相关阅读:
    [codeforces] 97B Superset || 平面分治
    [hdu] 5696 区间的价值 || 序列分治
    [zoj] 1937 [poj] 2248 Addition Chains || ID-DFS
    [poj] 2286 The Rotation Game || ID-DFS
    [codeforces] 25E Test || hash
    luogu P1196 银河英雄传说
    luogu P1357 花园
    luogu P1156 垃圾陷阱
    luogu P1127 词链
    luogu P1131 时态同步
  • 原文地址:https://www.cnblogs.com/dudu/p/4589458.html
Copyright © 2011-2022 走看看