Get and post values in the Web Api, apiget

Source: Internet
Author: User

Get and post values in the Web Api, apiget
GET Method

The get method is generally used to obtain data for conditional filtering, that is, "query"

1. No Parameters

var look = function () {        $.ajax({            type: "GET",            url: "http://172.28.20.106:8002/api/products/",            dataType: "xml",            contentType: 'application/xml;charset=gb2312;'        }).success(function (res) {            console.log(res);        }).error(function (xhr, status) {            console.log(xhr);        });    }

2. One Parameter

Var look = function () {$. ajax ({type: "GET", url: "http: // 172.28.0000106: 8002/api/users/", data: {"id": 2}, dataType: "xml", contentType: 'application/xml; charset = gb2312 ;'}). success (function (res) {console. log (res );}). error (function (xhr, status) {console. log (xhr );});}
The background Controller method is as follows:
  // GET api/users/5        public string Get(int id)        {            return "id:"+id;        }

Of course, you can also put the parameter in the url

   var look = function () {        $.ajax({            type: "GET",            url: "http://172.28.20.106:8002/api/users/2",            dataType: "xml",            contentType: 'application/xml;charset=gb2312;'        }).success(function (res) {            console.log(res);        }).error(function (xhr, status) {            console.log(xhr);        });    }

Output: <string xmlns = "http://schemas.microsoft.com/2003/10/Serialization/"> id: 2 </string>

3. Multiple simple parameters

The background method is as follows:
 // GET api/users/5        public string Get(int id,string name)        {            return "id:" + id+" name:"+name;        }

You can simply specify multiple parameters.

Var look = function () {$. ajax ({type: "GET", url: "http: // 172.28.0000106: 8002/api/users", data: {"id": 2, "name ": "Zhang Fei"}, dataType: "json", contentType: 'application/json; charset = gb2312 ;'}). success (function (res) {console. log (res );}). error (function (xhr, status) {console. log (xhr );});}
Output: "id: 1 name: Zhang Fei"

 

4. Pass an object
The background method is as follows:
       [Route("Manger")]        public string Get( Product model)        {            return "id:" + model.Id + " name:" + model.Name;        }

You may notice that there isMarkThis is actually a custom route. For heavy-load methods, it prevents errors from Matching Multiple Adaptive methods.




It must be emphasized that it is not a matter of course to construct an object and pass it over.
Var look = function () {var Product = {Id: 1, Name: "Zhang Fei", Category: "212", Price: 22 };$. ajax ({type: "GET", url: "http: // 172.28.0000106: 8002/api/users/Manger", // data: {"model ": {"Id": 2, "Name": "Zhang Fei", "Category": "22", "Price": 22 }}, data: Product, dataType: "json", contentType: 'application/json; charset = gb2312 ;'}). success (function (res) {console. log (res );}). error (function (xhr, status) {console. log (xhr );});}
Errors are reported in both cases.
After multiple tests, it is found that the backend method parameter list is added
[FromUri] the keyword is enough.
The method is as follows:
[Route ("Manger")] public string Get ([FromUri] Product model) {return "id:" + model. Id + "name:" + model. Name ;}

Output: "id: 1 name: Zhang Fei"

 

POST method

The post method is generally used for adding, deleting, and modifying. However, in the web api, THE post method is only used for adding and modifying operations.

Let's take a look at what the template has generated for us.

       // PUT api/users/5        public string Put(int id, [FromBody]string value)        {            return "id:" + id + "value:" + value;        }        // DELETE api/users/5        public void Delete(int id)        {        }

1. A post Parameter

Note:: Post submission is required

[FromBody] keyword, and the parameter list can only have one keyword, multiple are invalid

 

 

// POST api/users [Route ("addid")] public string Post ([FromBody] string value) {return "value:" + value ;}

 

Inertial thinking, and then our front-end will write it like this

        $.ajax({            type: "POST",            url: "http://172.28.20.106:8002/api/users/addid",            data: {"value":"1"}        }).success(function (res) {            console.log(res);        }).error(function (xhr, status) {            console.log(xhr);        });

The output result shows that the value is :"

No data is received in the background

Summary:

When there is only one parameter, there are two ways to get the value

1. data: {"": "1"} // ignore parameter name
2. data: "= 1" // Add "=" and remove curly braces
     $.ajax({            type: "POST",            url: "http://172.28.20.106:8002/api/users/addid",            data: {"":"1"}        }).success(function (res) {            console.log(res);        }).error(function (xhr, status) {            console.log(xhr);        });
    $.ajax({            type: "POST",            url: "http://172.28.20.106:8002/api/users/addid",            data: "=1"        }).success(function (res) {            console.log(res);        }).error(function (xhr, status) {            console.log(xhr);        });

Output: "value: 1"

2. Multiple parameters of post (1 Object)

Note: post cannot submit multiple parameters and can only be merged into objects.

Incorrect syntax:

Public string Post (int id, string name) {return "id is:" + id + "name:" + name ;}

Public string Post (int id, [FromBody] string name) {return "id is:" + id + "name:" + name ;}

Correct syntax:

[Route ("addmodel")]
Public string Post ([FromBody] Product value) {return "value:" + value. Id + "name:" + value. Name ;}

Foreground call:

Var Product = {Id: 1, Name: "Zhang Fei", Category: "212", Price: 22}; $. ajax ({type: "POST", url: "http: // 172.28.0000106: 8002/api/users/addmodel", data: Product }). success (function (res) {console. log (res );}). error (function (xhr, status) {console. log (xhr );});

Output: "value: 1 name: Zhang Fei"

 

3. Multiple parameters of post (multiple objects)

If there are multiple objects, you can only encapsulate them in one extension object.

Public class User {public int ID {get; set;} public int Name {get; set ;}} public class Product {public int Id {get; set ;} public string Name {get; set;} public string Category {get; set;} public decimal Price {get; set ;}} // object extension class public class NewProduct {public User user {get; set;} public Product product {get; set ;}}

Next we will take the extension class as the parameter, and the background code will become like this

[Route ("addnewmodel")] public string Post ([FromBody] NewProduct value) {return "userid value:" + value. user. ID + "priduct value:" + value. product. name ;}

Next is the frontend call.

Var Product = {Id: 1, Name: "Mobile Phone", Category: "212", Price: 22}; var User = {Id: 1, Name: "Zhang Fei" ,};$. ajax ({type: "POST", url: "http: // 172.28.0000106: 8002/api/users/addnewmodel", data: {Product: Product, User: user }}). success (function (res) {console. log (res );}). error (function (xhr, status) {console. log (xhr );});

Output: "userid value: 1 priduct value: Mobile Phone"

 

You can also write it as follows:

$. Ajax ({type: "POST", url: "http: // 172.28.0000106: 8002/api/users/addnewmodel", data: {Product: {Id: 1, Name: "Mobile Phone", Category: "212", Price: 22}, User: {Id: 1, Name: "Zhang Fei ",}}}). success (function (res) {console. log (res );}). error (function (xhr, status) {console. log (xhr );});

 

Custom route
I would like to introduce it because it is widely used in my code.
Use Cases: used for method overloading to ignore custom URLs of method names (better)

Procedure:
1. Add a tag above the Controller class
   [RoutePrefix("api/users")]    public class UsersController : ApiController    {    }

The content can be defined according to your preferences.

2. Add the Route tag [Route ("Manger")] to the method.

      [Route("Manger")]        public string Get([FromUri] Product model)        {            return "id:" + model.Id + " name:" + model.Name+" price:"+model.Price;        }

In this way, you can use

Api/users/Manger

 

Note:: If you want to implement step 1, you must first implement step 1. Otherwise, an error will be reported.

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.