ASP. NET MVC Learning Series (ii)-WEBAPI request (RPM)

Source: Internet
Author: User

Transferred from:

Go ahead. asp. NET MVC Learning Series (i)-webapi a look at the get and post requests that are initiated on the general foreground page, how we handle them in the Web API.

Here I use JQuery to initiate asynchronous requests for data invocation.

Continue to use the example from the previous article, add a index.html page, and add a reference to jquery.

One, no parameter GET request

A general GET request can be implemented using the $.get () or $.ajax ({type: "get"}) provided by jquery:

The requested background action method is still GetUser () in the previous article:

You can also get the return data correctly using the $.ajax ({type: "Get"}):

Second, a GET request that passes a parameter

Usually we need to pass parameters just to specify the data property of the Ajax method: data:{"name": "Zhao da Bao"}

The correct return data in the background:

Three, a GET request that passes two or more parameters

According to the above method, for more than one parameter we can easily write: data:{"name": "Zhao Bao", "Age": 12}

The correct return data in the background:

Iv. POST request with no parameters

We can use $.post () or $.ajax ({type: "POST"}) to initiate a POST request:

The data is returned correctly in the background:

V. Pass a POST request for a parameter:

First of all, we need to remind you that after we have modified the background code, if we do not rebuild the project, then the request will be error: "The request matching HTTP resource not found":

So, as long as we modify the background code, we must regenerate it:

However, when we re-build the project, send the request again, see the 404 error again, check the code again, and don't find out where the problem is.

  In fact, the ASP. NET Web API can correctly identify our Usercontroller controller for processing Post/api/user, but cannot find an acceptable way to process the request.

That is, the Web API receives a request to find the user controller, but cannot find the action with the name def in the controller.

So how are we going to fix it?

By searching the instructions on the website of the Web API on MSDN, we can find the following section:

That is , in the action method we need to use the [Frombody] property label to indicate the property .

After the modification, send the request again, we can see that the Status Code is 200, the request sent successfully.

As you can see, in a POST request, the parameter of the method must be decorated with the [Frombody] property, [Frombody] tells the web API to get the value of the parameter from the POST request weight.

But what surprises us is that the value of name in the data returned in the background is empty.

With debugging, we can see that the name value received in the background action is null.

Through the above tests I can also guess that the Web API requires the [frombody] parameter of the request to be passed, there must be a specific format in order to be properly obtained. This particular format is not a common form of Key=value's key-value pairs. The model binder for the Web API wants to find a value in [frombody] that does not have a key name, that is, not key=value, but =value.

Now, let's set the key in data to null and send the request again:

The test is visible and the data is received correctly in the background:

Vi. Post requests that pass two parameters

Supposedly, a parameter of the request implementation, then pass two or more parameters are very smooth, for two parameters of the background receive method, we may write:

But it turns out that this is wrong.

So how do we define two or more parameters?

Once again look at the official website of the introduction, we learned that:

In other words, the[frombody] modifier can have only one parameter . We need to encapsulate the multiple parameters passed.

Here, we can encapsulate name and age as a student class:

The front page sends the request again:

The Status code is 200, the request succeeds, and the data returned to the background is correctly obtained:

Here, we can see through the request header data in the above image, the format of form data is key=value&key=value this form name=%e8%b5%b5%e5%a4%a7%e5%ae%9d&age=13, We usually use a more general JSON format. Here, we use Json.stringify () to serialize the data.

Send the request again:

You can see that the format of the data in from data is a JSON string, the Status code is 200, the request is correct, but the result is wrong, the background is not receiving data parameters:

So where does the problem really go?

We look at the request header again, noting that although the data format we passed is a JSON string, the Content-type in the request header is

Application/x-www-form-urlencoded, not the JSON format for the Application/json. The encoding format, application/x-www-form-urlencoded, indicates that the form data is encoded as a name/value pair.

Here, I want to say a point of attention. usually when we use JSON data, it is easy to forget to specify Content-type as "Application/json", so it is easy to cause a lot of "unexpected" errors.

So, we specify Content-type in $.ajax ():

This time, the backend correctly received and returned the data:

Vii. Post requests that pass multiple parameters

With the above experience, we can easily write a POST request that passes multiple parameters:

The background receives and returns data:

Eight. Post requests that pass multiple different objects

Sometimes we also encounter the need to pass several different object parameters, for this particular situation in Json.NET provides us with a generic object called Jobject, we can use the. Object name to dynamically traverse the value of the property inside the parameter, Then the dynamic conversion and the corresponding property type in the JSON type.

Like what:

Background debugging, which gets the value of the property by Dynamic transformation:

The data is returned correctly in the background:

Nine, get different types of data

Generally we get back to the background the data format type is JSON format, we can also specify the output type in the request header to obtain different return type data:

Specifies that the output type is in XML format:

Specifies that the output type is in JSON format:

Basically here, the main content of this article is even finished, the focus of the post request for the processing of parameters is important to note.

Above we in the process of testing, all through the controller class to create their own parameters to receive processing, it may be asked, we have to write in the end whether it conforms to the specification, the WEB API default is how to deal with it? Here, in Visual Studio, we have our own WEB API Controller class:

We can add a new item to select the WEB API controller class to:

Here we can see that in the Controller class created by default, the action method for the POST request has its own [Frombody] property. Now I don't have to say, you already know why it takes a [Frombody] property for a parameter by default!

Well, today's content is here, the following is attached to my reference several articles:

MSDN Introduction to [Frombody] in the Web API: Parameter Binding in ASP. NET Web API | The ASP. NET Site

Introduction to [Frombody] properties and POST parameter descriptions (e): Using jQuery to POST [frombody] parameters to Web API | Encosia

Translated version of the above Web article: "Translation" using the jquery post form to the Web API | Drifting North

Post multiple parameters to Web API summary: Post multiple parameters to Web API Controller Method Summary | Drifting North

Code attached to the current project: XWEBAPIDEMO-WEBAPI request

Reprint please indicate the source.

ASP. NET MVC Learning Series (ii)-WEBAPI request (RPM)

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: 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.