Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Web API Parameter binding in ASP.NET

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the example analysis of Web API parameter binding in ASP.NET, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

The operation method can have one or more different types of parameters in the WebAPI controller. It can be a basic data type or a complex type. WebAPI binds the parameters of the action method based on the query string of the URL or the parameter type in the request body.

If the parameter type is a basic data type (int,double,string,DateTime,bool, etc.), WebAPI will get the parameter value from URL by default (that is, through querystring).

If the parameter type is a complex type, WebAPI acquires the parameter value from the request body by default.

The following table lists the default rules for Web API parameter binding.

HTTP method Query StringRequest BodyGET simple type cannot get parameter values from the request body POST simple type complex type PUT simple type complex type PATCH simple type complex type DELETE simple type cannot get parameter values from the request body

Let's first look at how the Values controller that is automatically generated when you create a Web API project with MVC is defined.

Using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;namespace WebAPIContainMVC.Controllers {public class ValuesController: ApiController {/ / GET api/values public IEnumerable Get () {return new string [] {"value1", "value2"} } / / GET api/values/5 public string Get (int id) {return "value" } / / POST api/values public void Post ([FromBody] string value) {} / / PUT api/values/5 public void Put (int id, [FromBody] string value) {} / / DELETE api/values/5 public void Delete (int id) {}}

From the definition of Values controller, we can draw the following conclusions:

(1) there are four conventional methods of WebAPI: Get (), Post (), Put () and Delete ().

(2) the parameters of the four methods can be classified into two categories: URL transfer (Request-url) and Body (Request-body) transfer.

(3) the parameter transfer of the four methods can be classified into two categories, and these two categories are concentrated in Get and Post (Put is the combination of Get and Post, Delete and Get type), so to study the parameter binding of WebAPI, we only need to study the parameter transfer of Get and Post methods, and Get corresponds to Request-url,Post corresponding to Request-Body.

In this article, client calls are tested using the Fiddler tool.

1. Get1, basic data types as method parameters 1.1.The method contains only one parameter (formal parameters can be passed in)

The method is defined as follows:

Using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Web.Http;using WebAPIContainMVC.Entity;namespace WebAPIContainMVC.Controllers {public class StudentController: ApiController {[HttpGet] public string GetStudentById (int id) {string strResult=string.Empty; List list = new List () Student stu = new Student () {StudentId=1, Name= "Tom", Age=20, Sex= "male"}; list.Add (stu) List.ForEach (p = > {if (p.StudentId.Equals (id)) {strResult = "the student information exists";} else {strResult = "Sorry, the student information cannot be found" }}); return strResult;}}

Client call

Results:

Double-click the process on the left to get the following result

1.2. The method contains multiple parameters (formal parameters can be passed in)

The method is defined as follows:

Public string GetStudentByIdAndName (int id,string name) {string strResult = string.Empty; List list = new List (); Student stu = new Student () {StudentId = 1, Name = "Tom", Age = 20, Sex = "male"}; list.Add (stu) List.ForEach (p = > {if (p.StudentId.Equals (id) & & p.Name.Equals (name)) {strResult = "the student information exists" } else {strResult = "Sorry, the student information cannot be found";}}); return strResult;}

URL address: http://localhost:63512/api/student?id=1&&name=Tom

The results are as follows:

2. Entity object type as method parameter (formal parameter cannot be passed in)

The method is defined as follows:

[HttpGet] public string GetStudent (Student student) {string strResult = string.Empty; List list = new List (); Student stu = new Student () {StudentId = 1, Name = "Tom", Age = 20, Sex = "male"}; list.Add (stu) If (student! = null) {list.ForEach (p = > {if (p.StudentId.Equals (student.StudentId)) {strResult = "this student information exists" } else {strResult = "Sorry, the student information cannot be found";}});} else {strResult = "Parameter value is Null" } return strResult;}

The result of the client call is as follows:

3. Basic data types and entity objects are mixed as method parameters (basic data types can be passed in, entity objects cannot be passed in) 4. Summary

(1) the query string parameter name and the operation method parameter name must be the same (case-insensitive). The order of parameters can be inconsistent.

(2) the essence of Get () parameter passing is URL string concatenation, but the length of URL string is limited.

(3) the parameters of Get () support basic data types, but not entity data types.

(4) the Get () parameter is passed in the header of the Http request, but Request-Body is not supported.

(5) the method of Get type should be named as "Get+ method name" as far as possible, and the feature [HttpGet] should be added before the method.

II. Post

1. The Post parameter is passed within the Request-Body.

2. Post parameters can pass either basic data types or entity data types.

3. The Post operation method can only contain one entity data type, because only one parameter is allowed to read the data in Request-Body.

4. When passing parameters in Post, both basic type parameters and entity types need to rely on the [FromBody] feature. (in some cases, you can pass parameters in without writing the [FromBody] feature, but for normalization, it's best to add this feature.)

5, Post type method naming, try to use the "Post+ method name" naming way, in front of the method with the feature: [HttpPost].

III. FromURI and FromBody

By default, WebAPI gets the values of basic data type parameters from the query string and complex type parameters from the request body. What if you want to change this default?

You can use the [FromURI] attribute, which is WebAPI to get the value of the complex type parameter from the query string, and the [FromBody] attribute to enable WebAPI to get the value of the basic data type parameter from the request body.

For example, the following Get method

[HttpGet] public string GetStudentById ([FromUri] Student stu) {}

The Get method includes complex type parameters, the parameter adds a [FromUri] attribute, and WebAPI will try to get the value of the Student type parameter from the query string.

Again, refer to the following Post method:

[HttpPost] public string Post ([FromBody] string name) {}

WebAPI will get the value of the base type parameter from the request body, not from the request string.

Thank you for reading this article carefully. I hope the article "sample Analysis of Web API Parameter binding in ASP.NET" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report