I downloaded the source code of asp.net mvc 4 and checked it out. However, I personally think that the Web API in MVC4 beta is quite good, although it is a traditional regression. The best web api is that it is more suitable for ajax calls using jquery.
Here I will mainly explain how to use the Web API features in asp.net mvc 3 to make AJAX calls cool.
First, let's take a look at the Response of asynchronous calls in the traditional asp.net mvc 3:
The Action is as follows:
The corresponding jquery ajax Request Code (only simple code ,):
Let's take a look at the Response information:
Response Header Information:
The status code is 200 OK. Green,
Returned JSON data:
Now we want to use the Status defined by http.net to return different Status codes based on different operations. For example, when a record is successfully created, we return 201 success. If no permission is available, we do not have the permission to return.
Now we try to modify the Action as follows:
Just add a line of code: Response. StatusCode, that is, this Action is the information of the creator. when the information is successfully created, return to the browser and say: Hi, the creation is successful. In the past, you may have used jquery's ajaxSuccess to perform subsequent operations. Well, now you can determine which step to perform by judging the status code obtained by the client.
Try to run:
At this time, you can see that the status code we get is 201, and the corresponding Response Header information:
It is not 200 OK, but 201 Created.
In the Asp.net http.net namespace, many Status codes are defined:
Here you may think that this method can be used for unified processing of AJAX requests in terms of security. When a request has no permission, we use a Filter to tell it that Hi, this request is not allowed, and the status code in the red box is 400. If it is a Web request, you can transfer the requester to the login page, balabara...
First, we need to define a Filter:
Use this Filter in PostPerson Action:
After compilation, run:
The Status Code is 400 or Bad Request. The corresponding Response certainly does not have data. In the ajax request of jquery, we can determine that when the status code is 400, location. href = "any where ha ":
Cheers
From Einstein's timeline