能省则省:在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

posted @ 2015-06-19 18:33  dudu  阅读(6186)  评论(12编辑  收藏  举报