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.