• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

能省则省:在ASP.NET Web API中通过HTTP Headers返回数据

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

对于一些返回数据非常简单的 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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap