What is parameter binding in C# ASP.NET WebAPI?

王林
Release: 2023-09-13 17:33:03
forward
1286 people have browsed it

C# ASP.NET WebAPI 中的参数绑定是什么?

Binding is the process of setting parameter values ​​when Web API calls the controller How to do it.

Web API methods with different types of parameters and how to customize them Binding process.

If the parameter is a simple type such as int, bool, double, etc., Web API will try to get the value from the URI (from routing data or from the query string)

If the parameter is a complex type, such as Customer , Employee, etc., then Web API The framework attempts to get the value from the request body.

We can change the default behavior of the parameter binding process using the following method [FromBody] and [FromUri] properties.

FromUri -

If the parameter is a simple type, Web Api will try to get it from URI

.NET basic types, such as double, DateTime, GUID String, any type that can be used Converting from String type

Example

public Student Get(int id){}
Copy after login

FromBody

If the parameter type is Complex type, then Web Api will try to bind the value from Message text.

Example

Public Student Post(Employee employee){}
Copy after login

[FromUri]

To force the Web API to read complex types from the URI, add the [FromUri] attribute To the parameters

Use the [FromUri] attribute to force the Web Api to get the value of type Complex from Query string.

Example

public Student Get([FromUri] Employee employee)
public HttpResponseMessage Get([FromUri] Employee employee) { ... }
Copy after login

[FromBody]

Use the [FromBody] attribute to get the Primitive type value from the request body, Contrary to the default

No, multiple FormBody is not allowed in a single operation.

To force Web API to read a simple type from the request body, add [FromBody]

In this example, Web API will use the media type formatter to read the value of name From request body

Example

public Student Post([FromBody] string name]){...}
public HttpResponseMessage Post([FromBody] string name) { ... }
Copy after login

The above is the detailed content of What is parameter binding in C# ASP.NET WebAPI?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template