Go C # Advanced Series--webapi interface return value not confused: return value type detailed

Source: Internet
Author: User

This article transferred from: http://www.cnblogs.com/landeanfen/p/5501487.html

Read Catalogue

    • One, void no return value
    • Second, Ihttpactionresult
      • 1. Json (T content)
      • 2, OK (), OK (T content)
      • 3, NotFound ()
      • 4. Other
      • 5, the implementation of the custom Ihttpactionresult interface
    • Third, Httpresponsemessage
    • Iv. Custom Types
    • V. Summary

Body

Preface: Have not written something for one months, feel the heart empty. Today, a dry, want to learn webapi of the park friends quickly move up, follow the Bo master to learn it. Previously shared a C # Advanced series--WEBAPI Interface transfer parameter no longer confused: The description of the content of this blog post is very basic, did not expect to arouse a lot of interest, thank you for your support. As a program ape, we all know that parameters and return values are inseparable in the field of programming, and previously shared the Webapi of the next, and today we look at another important and fundamental knowledge point in Webapi: the return value. Or that sentence: This article for the beginning of the use of WEBAPI students, comparative basis, interested and look.

WEBAPI Series Articles

    • C # Advanced Series--webapi Interface test tool: Webapitestclient
    • C # Advanced Series--webapi cross-domain problem solution: CORS
    • C # Advanced Series--webapi Identity Authentication solution: Basic BASIC Certification
    • C # Advanced Series--WEBAPI Interface transfer parameter no longer confused: The explanation of the transfer parameter
    • C # Advanced Series--webapi interface return value not confused: return value type detailed
    • C # Advanced Series--webapi Exception handling solution
    • C # Advanced Series--webapi Regional Area usage Summary

Friends who have used webapi should know that there are four main types of interface return values for WEBAPI

    • void no return value
    • Ihttpactionresult
    • Httpresponsemessage
    • Custom Types

This article revolves around the four blocks to see how they are used.

Go back to the top of one, void no return value

void keyword We are not unfamiliar, it declares that the method does not return a value. It's also very simple to use, so let's look at an example to see.

public class ORDER    {public        string ID {get; set;}        public string NO {get; set;}        public string NAME {get; set;}        public string DESC {get; set;}    }
public class Ordercontroller:apicontroller    {        [httppost] public        void Saveorder (ORDER name)        {             // Working with business logic
} }

Call inside the web

$ (function () {    $.ajax ({        type: ' Post ',        URL: ' Http://localhost:21528/api/Order/SaveOrder ',        data : {ID: "AAA", NAME: "Test"},        success:function (data, status) {            alert (data);});}    );

Get results

As you can see, using the Void declaration method, the return value is not found in the success method, and an HTTP status code of 204 is returned, telling the client that the request does not return a value.

Back to top two, Ihttpactionresult

The Ihttpactionresult type is a very important type of return value in Webapi. Below are some of the uses of this type of return value, based on some of the most frequently used methods in the project.

Back to top 1, json<t> (T content)

Friends who have developed with MVC must remember that in MVC, the return value type of the interface that requested the data is mostly jsonresult, and you must have written an interface like this in MVC:

Public Jsonresult GetResult ()        {            return Json (new {}, Jsonrequestbehavior.allowget);        }

So, is there a similar usage in WEBAPI? Oh, at this point, Microsoft is always intimate. In the abstract class of Webapi's Apicontroller, we encapsulate the json<t> (T content) method, which is basically similar to the Jsonresult in MVC. Let's use an example to illustrate its usage:

[HttpGet]        Public Ihttpactionresult GetOrder ()        {            var lstres = new list<order> ();             In the actual project, the collection is assigned to the Lstres variable through a background fetch. This is just a test.            Lstres.add (New ORDER () {ID = "aaaa", NO = "111", NAME = "111", DESC = "1111"});            Lstres.add (New ORDER () {ID = "bbbb", NO = "222", NAME = "222", DESC = "2222"});            Return json<list<order>> (lstres);        }

To see this code, some people wonder, we define the return value type is the Ihttpactionresult type, directly return to json<t> (T content) This is feasible? We'll go to the definition of JSON to see:

        

We continue to move jsonresult<t> to the definition

The original jsonresult<t> is the realization of the Ihttpactionresult interface, no wonder you can directly return it.

Knowing this, we invoke it directly in the web via an AJAX request:

$ (function () {    $.ajax ({        type: ' Get ',        URL: ' Http://localhost:21528/api/Order/GetOrder ',        data: {},        success:function (data, status) {            alert (data);        }    );});

To see the results:

Since entity classes can be passed directly like this, if we want to pass some anonymous types, because in many cases we need to return to the front end of the object does not have the corresponding entity to correspond, if we want to return anonymous object what to do? We know that here the json<t> (T content) must be passed a corresponding generic type, if it is anonymous type here is certainly not good pass. Fortunately there is our type of object, of course you can use dynamic, let's try it.

        [HttpGet]        Public Ihttpactionresult GetOrder ()        {                      return json<dynamic> (new {AA = "", BB = "CC"});        

The same test results:

Back to top 2, Ok (), ok<t> (T content)

In addition to json<t> (T content), there is another common method in Apicontroller: Ok (). Again, we'll go to OK () to define

Protected internal Virtual Okresult Ok ();

Okresult go To Definition

With this as a basis, we can be assured of the use of bold.

        [HttpGet]        Public Ihttpactionresult Getokresult ()        {            return Ok ();        }

Get results

Returning OK () means that no information is returned to the client and only the client request succeeds.

In addition to OK (), there is another overloaded ok<t> (T content).

        [HttpGet]        Public Ihttpactionresult Getokresult (string name)        {            return ok<string> (name);        }

This usage is similar to json<t> (T content) If you have to ask what the difference is, or how to choose both. Then my understanding is that if you are returning entities or entity collections, it is recommended to use Json<t> (t content), if you are returning the underlying type (such as int, string, and so on), use ok<t> (t content).

Back to Top 3, NotFound ()

The NotFound () method is sometimes required when you need to return a record to a client that is not found.

Protected internal Virtual Notfoundresult NotFound ();

Take a look at its usage scenarios

        [HttpGet]        Public Ihttpactionresult Getnotfoundresult (string id)        {            var lstres = new list<order> ();            In the actual project, the collection is assigned to the Lstres variable through a background fetch. This is just a test.            Lstres.add (New ORDER () {ID = "aaaa", NO = "111", NAME = "111", DESC = "1111"});            Lstres.add (New ORDER () {ID = "bbbb", NO = "222", NAME = "222", DESC = "2222"});            var ofind = Lstres.firstordefault (x = = X.id = = ID);            if (Ofind = = null)            {                return NotFound ();            }            else            {                return json<order> (Ofind);            }        }
$ (function () {    $.ajax ({        type: ' Get ',        URL: ' Http://localhost:21528/api/Order/GetNotFoundResult ',        data: {ID: "CCCC"},        success:function (data, status) {            alert (data);}}    );});

Get results

The NotFound () method returns a 404 error to the client.

Back to top 4, other

There are other methods that have specific uses for them. Post it here.

4.1, content<t> (HttpStatusCode statusCode, T value)
        [HttpGet]        Public Ihttpactionresult Getcontentresult ()        {            return content<string> (Httpstatuscode.ok, "OK");        }

Returns a value and an HTTP status code to the client.

4.2, Badrequest ()
        [HttpGet]        Public Ihttpactionresult Getbadrequest (order order)        {            if (string. IsNullOrEmpty (order.id))                return badrequest ();            return Ok ();        }

Returns an HTTP error of 400 to the client.

4.3. Redirect (String location)
        [HttpGet]        Public Ihttpactionresult Redirectresult ()        {            return Redirect ("http://localhost:21528/api/Order/ Getcontentresult ");        }

Redirect the request to a different location.

Back to top 5, customizing the implementation of the Ihttpactionresult interface

The above describes some of the common methods of implementing Ihttpactionresult interfaces built into the system. What if we need to customize the return of Ihttpactionresult?

Before we introduce it, it is necessary to take a look at the definition of the Ihttpactionresult type, and move Ihttpactionresult to the definition to see:

namespace system.web.http{    //Abstract:     //     defines a command that asynchronously creates an System.Net.Http.HttpResponseMessage.    Public interface Ihttpactionresult    {        //Abstract:         //     creates an System.Net.Http.HttpResponseMessage Asynchronously.        //Parameter:///CancellationToken://The         token to   monitor for     cancellation requests.        //Return Result:         //     A task that, when completed, contains the System.Net.Http.HttpResponseMessage.        Task<system.net.http.httpresponsemessage> Executeasync (CancellationToken CancellationToken);}    

This interface contains a unique method, Executeasync (), that will asynchronously create an httpresponsemessage instance to return to the client.

With this as a basis, let's customize a subclass of bootstraptable service-side pagination to demonstrate the use of custom Ihttpactionresult.

First, customize an implementation class

public class Pageresult:ihttpactionresult    {        object _value;        Httprequestmessage _request;        Public Pageresult (object value, Httprequestmessage request)        {            _value = value;            _request = Request;        }        Public task

The Pageresult object is then returned in the API interface

[HttpGet]        Public ihttpactionresult getpagerow (int limit, int offset)        {            var lstres = new list<order> ();            In the actual project, the collection is assigned to the Lstres variable through a background fetch. This is just a test.            Lstres.add (New ORDER () {ID = "aaaa", NO = "111", NAME = "111", DESC = "1111"});            Lstres.add (New ORDER () {ID = "bbbb", NO = "222", NAME = "222", DESC = "2222"});            var oData = new {total = lstres.count, rows = Lstres.skip (offset). Take (limit). ToList ()};            return new Pageresult (OData, Request);        }

Best, Ajax calls

$ (function () {    $.ajax ({        type: ' Get ',        URL: ' Http://localhost:21528/api/Order/GetPageRow ',        data : {limit:1,offset:1},        success:function (data, status) {            alert (data);});}    );

Get results

Back to the top of the three,Httpresponsemessage

The Httpresponsemessage object is mentioned in the previous custom Ihttpactionresult return type. It represents a message object that returns an HTTP response to the client (containing the HTTP status code and the message that needs to be returned to the client). This object also has its own unique usage scenario: This object needs to be used when returning HttpResponse to the client. To export as an example, due to the need to export the Excel file to the client browser, WEBAPI server needs to the Web client output file stream, this time the general Ihttpactionresult object inconvenient to solve the problem, So Httpreponsemessage came in handy. Let's take a look at its use example.

    Public Httpresponsemessage Export () {//fetch data var lstres = Orderbll.export ();            Populate Excel with data hssfworkbook workbook = new Hssfworkbook ();                        Createandfillsheet (workbook, Lstres);            Save to service var fileName = "Excel" + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". xls";            var strpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, @ "data\" + fileName); using (FileStream fs = new FileStream (strpath, FileMode.Create)) {workbook.                Write (FS); using (MemoryStream ms = new MemoryStream ()) {workbook.                Write (MS); }}//output to browser try {var stream = new FileStream (strpath, Filemod                E.open);                Httpresponsemessage response = new Httpresponsemessage (Httpstatuscode.ok); Response.         Content = new Streamcontent (stream);       Response.                Content.Headers.ContentType = new Mediatypeheadervalue ("Application/octet-stream"); Response. Content.Headers.ContentDisposition = new Contentdispositionheadervalue ("attachment") {F                Ilename = FileName};            return response;            } catch {return new httpresponsemessage (httpstatuscode.nocontent); }        }

Save the file stream inside the Streamcontent object and output it to the browser. You can output Excel from the browser side.

Back to top four, custom types

The above several return value types can solve the problem of most of our return value, of course, you can also Webapi interface and normal method, return any type,Webapi will automatically serialize you to customize any return type, and then write the serialized value to the response body, the status Code unified return 200 . Like what:

        [HttpGet]        public Object Getother ()        {            var lstres = new list<order> ();            In the actual project, the collection is assigned to the Lstres variable through a background fetch. This is just a test.            Lstres.add (New ORDER () {ID = "aaaa", NO = "111", NAME = "111", DESC = "1111"});            Lstres.add (New ORDER () {ID = "bbbb", NO = "222", NAME = "222", DESC = "2222"});            return lstres;        }

Get results

And the above JSON, OK and other usage on the effect is not much different.

Back to top v. Summary

The above four aspects in detail share the following WEBAPI the common usage of the return value inside, cannot say which way is best, because each way has its specific usage scene. bloggers feel that in order to standardize the Webapi interface, the return value of the general interface, as far as possible to use the Ihttpactionresult type as the return value, after all, is the Microsoft built-in things, we may consider a lot of things we do not consider . Of course, you may feel the trouble, you may say that directly and ordinary methods to use the same is not more cool, Bo Master originally had this idea, but the learning of Microsoft's things more after the discovery of a lot of things or adhere to a certain standard is better, at least maintenance up convenient. This is like the webapi+odata that bloggers have been working on recently, why it is not so much more convenient to standardize the restful style as it is to make such a standard set of things. If this article can help you, may wish to recommend , your recommendation is Bo Master continue to summarize the power!

Go C # Advanced Series--webapi interface return value not confused: return value type detailed

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.