Can save province: Return data via HTTP headers in ASP.

Source: Internet
Author: User

For some Web APIs that are very simple to return data, such as the "number of short messages in the unread station of a specified user" that we encountered today, the return data is a number, which is a bit extravagant if you return data via HTTP response body. Why not return directly via HTTP headers? Energy saving and environmental protection. So today in the ASP. NET Web API actually tried, proved to be feasible.

With Httpresponsemessage on the Web API server, it's easy to implement the code as follows:

 Public classmessagescontroller:apicontroller{[Route ("Api/messages/user-{userid}/unread/count")]     Public AsyncTaskintuserId) {        varUnreadcount =Ten; varResponse =Request.createresponse (Httpstatuscode.ok); Response. Headers.add ("X-result-count", unreadcount.tostring ()); returnresponse; }}

The calling client simply reads the data directly from the HTTP headers, eliminating the need to read from the HTTP response body (if the content.readasstringasync operation is omitted with HttpClient), thus saving resources. The code is as follows:

 Public classwebapitest{[Fact] Public AsyncTask Get_user_unread_message_count () {using(varClient =NewHttpClient ()) {Client. BaseAddress=NewSystem.Uri ("www.cnblogs.com"); varUserId =1; varResponse =awaitClient. Getasync ($"/api/messages/user-{userid}/unread/count"); if(response. Issuccessstatuscode) {varUnreadcount = Response. Headers.getvalues ("X-result-count").                FirstOrDefault ();                Console.WriteLine (Unreadcount); Assert.equal (Ten,int.            Parse (Unreadcount)); }            Else{Console.WriteLine (response).                StatusCode); Console.WriteLine (awaitResponse.            Content.readasstringasync ()); }        }    }}

Resources

Getting a count of returns seen by a RESTful request

Paging in ASP. NET Web api:using HTTP Headers

Can save province: Return data via HTTP headers in ASP.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.