What exactly should be the WEBAPI return type, which is a problem?

Source: Internet
Author: User
Tags webhost

Objective

Some problems only really encounter or use and more thinking will think, usually if as a self-study mentality to study will not consider too much, I slowly understand for those who have too much to learn or say more clearly and more specific, if you are not urgent to learn or need to master skills, Let's put it aside for a while, for example, now compare the fire of angular and react, I also took the time to learn, but the company does not need or have a special front-end you learn a lot of the actual use of seemingly nothing, in fact, just do a little basic understanding can, at least others asked also know twos, Do not see what others learn or fire what blindly follow suit, or according to their own actual situation to learn is the kingly way. This is not just about learning according to their own, the head of the dream of the project is being done, suddenly came up with an idea, why that can not, why does it exist? This article is coming out.

Topic Introduction

We know that in WEBAPI we use this for response results:

         Public Httpresponsemessage getresult<t>(T t)        {            return request.createresponse<t> (Httpstatuscode.ok, T);        }

In the project front-end in order to and other unified, encapsulated a set of response results and status code, requires the direct return of the object, so the above changes such as the following:

     PublicResult<list<person>>GetResult () {varresult =NewResult<list<person>>(); returnresult; }     Public classResult<t>: baseresult { PublicT Data; }     Public classBaseresult { Public stringMessage;  Public intStatus;  PublicErrorCode ErrorCode; }     Public enumErrorCode {...}

Looking at the above two methods, one is the result of the WEBAPI built-in response, the other is to return the custom response result directly.

As a result, I began to think that although both of these methods can get the results we want, but what difference does it make? More specifically, are there any performance differences in the data response?

WEBAPI response Results and custom response results both performance differences

These are the objects that need to be returned for processing, and some of us do not need to return any objects for processing such as directly returning void, while in webapi the corresponding need to return Ihttpactionresult such as a custom return is as follows:

    Public void GetFirst ()   {.....}

In Webapi, the following returns are performed:

    Public ihttpactionresult Getsecond ()   {     return  OK ();               }

Let's test the difference between webhost and selfhost in the console separately, how do we get the difference? We took the time to compare the void method and the HTTP method by issuing 1000 requests in the console to obtain it altogether.

Selfhost
[HttpGet] Public voidGetFirst () {StringBuilder StringBuilder=NewStringBuilder ();  for(inti =0; I < -; i++) {StringBuilder. Append ("something"); }} [HttpGet] PublicIhttpactionresult Getsecond () {StringBuilder StringBuilder=NewStringBuilder ();  for(inti =0; I < -; i++) {StringBuilder. Append ("something"); }            returnOk (); }

The methods in the console are as follows:

        Private Const stringVoidurl ="Http://localhost:8080/api/home/GetFirst"; Private Const stringHttpurl ="Http://localhost:8080/api/home/GetSecond"; Private StaticList<timespan> Voidtimes =NewList<timespan>(); Private StaticList<timespan> Httptimes =NewList<timespan>(); Static voidMain (string[] args) {Console.WriteLine ("Start Test ....");  for(inti =0; I < +; i++) {Voidtimes.add (GetResponse (Voidurl)); Thread.Sleep (Ten); Console.WriteLine ("void Test"+i); } Console.WriteLine ("finished Void Test");  for(inti =0; I < +; i++) {Httptimes.add (GetResponse (Httpurl)); Thread.Sleep (Ten); Console.WriteLine ("http Test"+i); } Console.WriteLine ("finished Http Test"); varVoidtotaltime = voidtimes.sum (t =t.milliseconds); Console.WriteLine ("The void method requires a total of time to issue 1000 requests:"+voidtotaltime); Console.WriteLine ("The void method requires an average of time per request:"+ Voidtotaltime/1000.00+"seconds"); varHttptotaltime = httptimes.sum (t =t.milliseconds); Console.WriteLine ("The HTTP method makes 1000 requests with a total time required:"+httptotaltime); Console.WriteLine ("The HTTP method requires an average of time per request:"+ Httptotaltime/1000.00+"seconds");        Console.read (); }        StaticTimeSpan GetResponse (stringURL) {            varStopWatch =NewStopwatch ();            Stopwatch.start (); varHttpClient =NewHttpClient (); Httpclient.baseaddress=NewUri (URL); varTask =Httpclient.getasync (httpclient.baseaddress).            Result; varresult = task. Content.readasasync (typeof(Object)); varTimeSpan =stopwatch.elapsed;            Stopwatch.stop (); returnTimeSpan; }

Let's take a visual demonstration of the entire process:

From the above, it seems that the HTTP method saves a bit of time, and we will make the following changes to the number of methods in the above:

             for (int0200000; i++)            {                StringBuilder. Append ("something");            }

Then we'll look at the results:

When there are 200,000 of data, it saves a little bit at this time. Next we'll test the webhost.

Webhost

In webhost we use attributes to manage the request method:

[HttpGet] [Route ("test/void")]         Public voidGetFirst () {StringBuilder StringBuilder=NewStringBuilder ();  for(inti =0; I < -; i++) {StringBuilder. Append ("something"); }} [HttpGet] [Route ("Test/ihttpactionresult")]         PublicIhttpactionresult Getsecond () {StringBuilder StringBuilder=NewStringBuilder ();  for(inti =0; I < -; i++) {StringBuilder. Append ("something"); }            returnOk (); }

At this point, the console request address for the corresponding modification can be:

Private Const string " http://localhost:2531/test/void "  Privateconststring"http://localhost:2531/test/ Ihttpactionresult";

The results of this presentation are as follows:

It was now nearly a second. At this point we increase the data to the same 200,000 and then look at:

It's still 1 seconds faster now. If it's over here, let's take a look at it.

When we request the Void method, the status code returned is as follows:

At this point, HTTP is used to respond to the following:

The return status is also different, we need to have a corresponding processing method.

Summarize

When demonstrating the void method and the HTTP method, there are times when the HTTP method is slower than the void method, and for some reason, it is theoretically faster to use httpresponsemessage as the response result. Because the Httpresponsemessage built-in handles some exceptions and returns the corresponding status code, the Void method does not do any processing. But from another point of view, if we customize a set of returned status code to deal with it is not not, the individual feel that the use of WEBAPI built-in httpresponsemessage response mechanism to the best response to the results, look forward to your criticisms and answers, and do not know whether the test is reasonable. At that time, I also looked up the relevant information, and really did a similar test, so borrowed a bit.

Reference: Http://stackoverflow.com/questions/22689888/webapi-2-is-a-void-response-faster-then-ihttpactionresult

What exactly should be the WEBAPI return type, which is a problem?

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.