WebApi interface parameters are no longer confused: pass-through explanation

Source: Internet
Author: User
Tags http post

Read Catalogue

    • One, GET request
      • 1. Basic type parameters
      • 2, the entity as a parameter
      • 3. Array as parameter
      • 4. "Weird" GET request
    • Second, POST request
      • 1. Basic type parameters
      • 2, the entity as a parameter
      • 3. Array as parameter
      • 4, the background send request parameter delivery
    • Third, put request
      • 1. Basic type parameters
      • 2, the entity as a parameter
      • 3. Array as parameter
    • Iv. Delete Request
    • V. Summary

Body

Preface: Still remember just use WEBAPI when, by its transmission mechanism toss for a long time, consulted half-day information. Today, the use of WEBAPI also has a period of time, today, the API interface to record some of the ways and means of communication, is a note, but also hope to help beginners less detours. This article is aimed at beginning to use Webapi's classmates, the comparison Foundation, has the interest and looks.

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

This article intends to get, post, put, delete four ways to talk about the basic types (including Int/string/datetime, etc.), entities, arrays and other types of parameters how to pass.

Back to top one, GET request

For fetching data, the most we should use is a GET request. Here are a few examples to see our GET request parameter passing.

Back to top 1, base type parameters
[Httpget]public string getallchargingdata (int id, string name) {    return "chargingdata" + ID;}
$.ajax ({        type: "Get",        URL: "Http://localhost:27221/api/Charging/GetAllChargingData",        data: {id:1, name : "Jim", Bir: "1988-09-11"},        success:function (data, status) {            if (status = = "Success") {                $ ("#div_test"). htm L (data);}}    );

Parameter effects

This is the most basic way to pass the parameters of Get requests, nothing special.

Back to top 2, entity as parameter

If we want to pass the entity object arguments directly to the background when we get the request, is it possible? Let's take a look.

    public class Tb_charging {//<summary>///        PRIMARY Key ID///</summary> public        string ID {get ; Set }///<summary>///        Charging device name///</summary> public        string name {get; set;}        <summary>////        Charging Device description///        </summary> public        string DES {get; set;}        <summary>//creation time///        </summary> public        DateTime createtime {get; set;}    }
[Httpget]public string Getbymodel (tb_charging oData) {     return "chargingdata" + odata.id;}
$.ajax ({        type: "Get",        URL: "Http://localhost:27221/api/Charging/GetByModel",        contentType: " Application/json ",        data: {ID:" 1 ", NAME:" Jim ", Createtime:" 1988-09-11 "},        success:function (data, status) {
   if (Status = = "Success") {                $ ("#div_test"). HTML (data);}}    );

Test results

It is known that when a GET request, we direct the JSON object as an entity to pass the background, the background is not received. What is this for? Let's take a look at the corresponding HTTP request

Originally, get request, the default is to put all the parameters in the URL directly in the form of a string, the background is naturally not connected.

Cause Analysis: Remember the interview question asked about the difference between get and post requests? One difference is that the data of the GET request is appended to the URL (that is, the data is placed in the HTTP protocol header), and the post request is placed in the package body of the HTTP protocol packet.

According to the suggestions of the park friends, the GET request can be added to the parameter by adding [Fromuri] to the object directly. Or put the code on it:

    var postdata = {ID: "1", NAME: "Jim", Createtime: "1988-09-11"};    $.ajax ({        type: "Get",        URL: "Http://localhost:27221/api/Charging/GetAllChargingData",        Data:postdata,        success:function (data, status) {}    });
        [HttpGet]        public string Getallchargingdata ([fromuri]tb_charging obj)        {            return "chargingdata" + obj.id;        }

Get results:

If you do not want to use [Fromuri] These "weird" notation, which adds properties to the parameters, you can also use the method of first serializing and then deserializing back in the background.

$.ajax ({        type: "Get",        URL: "Http://localhost:27221/api/Charging/GetByModel",        contentType: " Application/json ",        data: {strQuery:JSON.stringify ({ID:" 1 ", NAME:" Jim ", Createtime:" 1988-09-11 "})},        succes S:function (data, status) {            if (status = = "Success") {                $ ("#div_test"). HTML (data);}}    );
        [HttpGet]        public string Getbymodel (string strquery)        {            tb_charging oData = Newtonsoft.json.jsonconvert.deserializeobject<tb_charging> (strquery);            Return "Chargingdata" + odata.id;        }

This will get our serialized object in the background, and then we can get the object by deserializing it.

Inside the URL we can see that it automatically adds an encoding to the object:

And as for the Friends of the park, they mentioned http://www.asp.net/web-api/overview/formats-and-model-binding/. PARAMETER-BINDING-IN-ASPNET-WEB-API model Binder This way, bloggers looked down and felt slightly complicated. If you are interested, you can try it. As for which way to pass the object, the garden friends can choose for themselves.

Back to top 3, array as parameter

The general GET request does not recommend an array as an argument because we know that the size of the GET request pass parameter is limited, with a maximum of 1024 bytes, and when the contents of the array are large, passing it as a parameter can result in the loss of parameter overrun.

Back to top 4, "weird" GET request

Why do you say get requests are "weird"? Let's look at the following two ways to compare.

(1) Webapi method name starts with get
    $.ajax ({        type: "Get",        URL: "Http://localhost:27221/api/Charging/GetByModel",        contentType: " Application/json ",        data: {strQuery:JSON.stringify ({ID:" 1 ", NAME:" Jim ", Createtime:" 1988-09-11 "})},        succes S:function (data, status) {            if (status = = "Success") {                $ ("#div_test"). HTML (data);}}    );
        [HttpGet]        public string Getbymodel (string strquery)        {            tb_charging oData = Newtonsoft.json.jsonconvert.deserializeobject<tb_charging> (strquery);            Return "Chargingdata" + odata.id;        }

This is the standard notation, background plus [HttpGet], parameters are normal:

For the sake of comparison, I'll remove [HttpGet] and then call

        [HttpGet] public        string Getbymodel (String strquery)        {            tb_charging oData = Newtonsoft.json.jsonconvert.deserializeobject<tb_charging> (strquery);            Return "Chargingdata" + odata.id;        }

There seems to be no problem! It is thought that if all get requests can omit [httpget] this annotation. We'll know when we try.

(2) Webapi method name does not start with get

We changed the previous method name from Getbymodel to Findbymodel, which is normal, many people do not want to use get start, and directly with the beginning of the query. What does it matter? There is no relation, we speak with facts.

    $.ajax ({        type: "Get",        URL: "Http://localhost:27221/api/Charging/FindByModel",        contentType: " Application/json ",        data: {strQuery:JSON.stringify ({ID:" 1 ", NAME:" Jim ", Createtime:" 1988-09-11 "})},        succes S:function (data, status) {            if (status = = "Success") {                $ ("#div_test"). HTML (data);}}    );
        [HttpGet]        public string Findbymodel (string strquery)        {            tb_charging oData = Newtonsoft.json.jsonconvert.deserializeobject<tb_charging> (strquery);            Return "Chargingdata" + odata.id;        }

It seems to be feasible, there is no problem. According to the above inference, we remove [HttpGet] is also feasible, good, we commented out [HttpGet], run up to try.

The result is no breakpoint , some people do not believe, we look in the browser HTTP request:

Hehe, this is strange, changed a method name, as for this? It's true!

Blogger's understanding is: The method name starts with GET, WEBAPI will automatically default this request is a GET request, and if you start with a different name and do not label the method of request, then this time the server found this method, but because the request method is not certain, so directly returned to you 405 --method is not allowed for errors.

Final conclusion: all WEBAPI methods are best combined with the requested way ([Httpget]/[httppost]/[httpput]/[httpdelete]), do not be lazy, so as to prevent similar errors, but also conducive to the maintenance of methods, People will know what this method is asking for at a glance.

This is why many people in the garden asked why the method name does not add [HttpGet] can not call the reason!

Back to top second, POST request

In Webapi's resetful style, the API service additions and deletions, respectively, corresponding to the HTTP Post/delete/put/get request. Let's talk about how the POST request parameters are passed.

Back to top 1, base type parameters

The arguments for the underlying type of the POST request are a little different from the GET request, and we know that the parameters for the GET request are passed through the URL, and the POST request is transmitted through the HTTP request body, and the WEBAPI Post request also takes the parameters from the HTTP request body.

(1) The wrong wording
    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        data: {NAME: "Jim"},        Success:function (data, status) {            if (status = = "Success") {                $ ("#div_test"). HTML (data);}}    );
        [HttpPost]        public bool SaveData (string NAME)        {            return true;        }

This is a very correct wording, but the reality is:

(2) Correct usage
    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        data: {"": "Jim"},        success:function (data, status) {}    });
        [HttpPost]        public bool SaveData ([frombody]string NAME)        {            return true;        }

This is a lot of other people's headache, but there is no way, so that it can really get our results:

Our general mechanism to take parameters through the URL is a key-value pair, that is, a certain key equals a value, and here the frombody and we generally through the URL parameter mechanism is different, its mechanism is =value, no key concept, and if you write a key ( For example, your Ajax parameter writes {name: "Jim"}), but the background gets the NAME equal to null. You can try it if you don't believe it.

All of this is about passing an underlying type parameter, so what if we need to pass multiple underlying types? According to the above inference, is it possible ([Frombody]string NAME, [frombody]string DES) to write like this? Try it and you'll know.

(1) Wrong wording
    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        data: {"" ":" Jim "," ":" Remarks "},        success:function (data, status) {}    });
        [HttpPost]        public bool SaveData ([Frombody]string NAME, [frombody] string DES)        {            return true;        }

Get results

This means that there is no way to take a value from multiple [frombody], and this method fails.

(2) Correct usage

Since the above approach does not work, how do we pass multiple basic types of data? A lot of the solution is to create a new class to contain the parameters passed, the blogger felt that this is not flexible, because if we each pass multiple parameters of the POST request to create a new class, our system then how many of this parameter class? It's a very troublesome thing to maintain. So bloggers feel that using dynamic is a good choice. Let's try that.

    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        contentType: ' Application /json ',        data:JSON.stringify ({NAME: "Jim", DES: "Remarks"}),        success:function (data, status) {}    });
        [HttpPost]        public object SaveData (Dynamic obj)        {            var strName = convert.tostring (obj.name);            return strName;        }

The dynamic type can successfully get multiple parameters, eliminating the burden of [frombody], and the transfer of AJAX parameters without using the "no nonsense" {"": "Value"} This style, there is a small fresh feeling ~ ~ One thing to note is that here in the AJAX request you need to add the parameter type JSON, which is contentType: ' Application/json ', this property.

(3) Recommended usage

We learned the convenience of the dynamic by requesting the delivery of the underlying type parameters above post, in order to avoid the "nonsense" notation of [frombody] this encumbrance and {"": "Value"}. Bloggers recommend that all underlying types be passed using dynamic, which facilitates the delivery of one or more parameters of the underlying type, as shown above. If the garden friends have a better way, welcome the discussion.

Back to top 2, entity as parameter (1) single entity as parameter

Above we solve the POST request basic type of data transfer problem through the dynamic type, then when we need to pass an entity as a parameter how to solve it? Let's look at the following code to know:

    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        data: {ID: "1", NAME: "Jim", Createtime: "1988-09-11"},        success:function (data, status) {}    });
        [HttpPost]        public bool SaveData (tb_charging oData)        {            return true;        }

Get results

Principle Explanation: using the entity as the parameter, the front-end directly passes the ordinary JSON, the background directly uses the corresponding type to receive can, does not have the frombody. But one thing to note here is that you cannot specify ContentType as Appplication/json, otherwise, parameters cannot be passed to the background. Let's take a look at what its default contenttype is:

To find out why, bloggers checked the type of HTTP Content-type. See the following instructions:

    • application/x-www-form-urlencoded: <form enctype= "" > Default enctype,form form data is encoded as key/ The value format is sent to the server (the format of the form's default submission data);
    • Application/json:json data format

This means that the POST request defaults to sending the Key/value form of the data inside the form to the service, and our server only needs the object with the corresponding Key/value attribute value to receive it. Using Application/json, however, means that the front-end data is passed to the backend with serialized JSON, and the back end is going to turn it into a solid object, and a deserialization process is required. According to this logic, if we specify ContentType as Application/json, then passing the serialized object should also be possible. Bloggers are curious, or want to try to the end, so there is the following code:

    var postdata = {ID: "1", NAME: "Jim", Createtime: "1988-09-11"};    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        contentType: ' Application /json ',        data:JSON.stringify (postdata),        success:function (data, status) {}    });
        [HttpPost]        public bool SaveData (tb_charging lstcharging)        {            return true;        }

Get results:

try to succeed, that is to say, both formulations are feasible. If you specify ContentType as Application/json, you must pass the serialized object, and if you use the default parameter type for the POST request, the front-end passes directly to the JSON-type object.

(2) The entity and the underlying type are passed together as parameters

There are times when we need to pass the underlying types and entities together in the background, and this time our magical dynamic comes in handy.

    var postdata = {ID: "1", NAME: "Jim", Createtime: "1988-09-11"};    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        contentType: ' Application/json ',        data:JSON.stringify ({NAME: "Lilei", Charging:postdata}),        success:function (data, Status) {}    });
        [HttpPost]        public object SaveData (Dynamic obj)        {            var strName = convert.tostring (obj.name);            var ocharging = newtonsoft.json.jsonconvert.deserializeobject<tb_charging> (convert.tostring (obj. charging));            return strName;        }

Get results:

The principle does not need to say more, ibid.

Back to top 3, array as argument (1) base type array
    var arr = ["1", "2", "3", "4"];    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        contentType: ' Application/json ',        data:JSON.stringify (arr),        success:function (data, status) {}    });
        [HttpPost]        public bool SaveData (string[] IDs)        {            return true;        }

Get results:

(2) Entity collection
    var arr = [        {id: "1", Name: "Jim", Createtime: "1988-09-11"},        {id: "2", NAME: "Lilei", Createtime: "1990-12-11" },        {ID: "3", NAME: "Lucy", Createtime: "1986-01-10"}    ];    $.ajax ({        type: "Post",        URL: "Http://localhost:27221/api/Charging/SaveData",        contentType: ' Application /json ',        data:JSON.stringify (arr),        success:function (data, status) {}    });
        [HttpPost]        public bool SaveData (list<tb_charging> lstcharging)        {            return true;        }

Get results:

Back to top 4, background send request parameter delivery

There are so many written on the front end of the AJAX request to do, we know that if the caller is not a Web project, such as an Android client, you may need to send HTTP requests from the background to call our interface method, if we go through the background to send the request is also feasible? Let's pass the write code with the entity object as a parameter to try it out.

    public void Testreques () {//request path String url = "Http://localhost:27221/api/Charging/SaveData";            Define the request and set the path to the request WebRequest request = WebRequest.Create (URL); Request.            Method = "POST";            Initialize the request parameter string postdata = "{ID: \" 1\ ", NAME: \" Jim\ ", Createtime: \" 1988-09-11\ "}";            Set parameter encoding format, solve Chinese garbled byte[] ByteArray = Encoding.UTF8.GetBytes (postdata); Set the MIME type and content length request for the request.            ContentType = "Application/json"; Request.            ContentLength = Bytearray.length; Open the request character stream stream DataStream = Request.            GetRequestStream ();            Datastream.write (ByteArray, 0, bytearray.length);            Datastream.close (); Define response for the preceding request response WebResponse response = Request.            GetResponse (); Gets the corresponding status code Console.WriteLine (((HttpWebResponse) response).            Statusdescription);    Define a stream of response characters        DataStream = Response.            GetResponseStream ();            StreamReader reader = new StreamReader (dataStream); String responsefromserver = reader.    ReadToEnd ();//Read All Console.WriteLine (Responsefromserver); }

When the code runs to request. GetResponse () In this sentence, the API enters a breakpoint

Try to succeed.

Back to top three, put request

Webapi put requests are typically used for object updates. It is basically the same as usage and post requests. also supported for [Frombody], you can also use dynamic.

Back to top 1, base type parameters
    $.ajax ({        type: "Put",        URL: "Http://localhost:27221/api/Charging/Update",        contentType: ' application/ JSON ',        data:JSON.stringify ({ID: "1"}),        success:function (data, status) {}    });
        [Httpput]        public bool Update (Dynamic obj)        {            return true;        }

Back to top 2, entity as parameter

Same as the POST request.

Back to top 3, array as parameter

Same as the POST request.

Back to top four, delete requests

As the name implies, delete requests are definitely for delete operations. The parameter passing mechanism and post are basically the same. The following is a simple example, other cases refer to the POST request.

    var arr = [        {id: "1", Name: "Jim", Createtime: "1988-09-11"},        {id: "2", NAME: "Lilei", Createtime: "1990-12-11" },        {ID: "3", NAME: "Lucy", Createtime: "1986-01-10"}    ];    $.ajax ({        type: "Delete",        URL: "Http://localhost:27221/api/Charging/OptDelete",        contentType: ' Application/json ',        data:JSON.stringify (arr),        success:function (data, status) {}    });
        [Httpdelete]        public bool Optdelete (list<tb_charging> lstchargin)        {            return true;        }

Back to top v. Summary

The above more detailed summary of WEBAPI various requests for the various parameters of transmission. Each case is Bo master actual code test, content is not difficult, but if just contact these things still need a little time to familiar with, here to do a summary, hope can help just contact Webapi of the park friends. If this article can help you, may wish to recommend , your recommendation is Bo Master continue to summarize the power!

Recently, I'm going to do something of my own, and merge some of the good technologies in the blog. Small partners with project cooperation hurry up and contact the blogger!

Original source of this article: http://www.cnblogs.com/landeanfen/

Welcome to reprint, but without the author's consent, reprint article must be in the article page obvious location to the author and the original link , otherwise reserve the right to pursue legal responsibility!

WebApi interface parameters are no longer confused: pass-through explanation

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.