Summary of problems in calling web Api methods using ajax, ajaxapi
1. Get request
1. There is no parameter Get request, which is the same as ajax requests.
$. Ajax ({
Url: '.../api/User/UserVerify,
Type: 'get ',
Success: function (json ){
Alert (json );
},
Error: function (){
Alert ("error ");
}
});
In this case, the api code of the background code can be directly public string UserVerify () {}, and the HttpGet feature must be added to the action.
2. Get requests with one or more parameters
$. Ajax ({
Url: '.../api/User/UserVerify? LoginName = admin & passWord = 123456 ',
Type: 'get ',
Success: function (json ){
Alert (json );
},
Error: function (){
Alert ("erroe ");
}
});
In this case, the background Api code can be public string LoginVerify (string loginName, string passWord) {}. you need to add the HttpGet feature to the action.
Ii. Post requests
1. Post requests without Parameters
$. Post (
'.../Api/User/UserVerify ',
Function (json ){
Alert (json );
});
In this case, the backend call needs to add the HttpPost feature on the Action, public string LoginVerify (){}
2. A parameter Post request
In a post request, the parameter of a method must be modified using the [FromBody] attribute. The [FromBody] tells the Web API to retrieve the parameter value from the post request weight. That is, it should be written as follows:
[HttpPost, ActionName ("UserVerify")]
Public string LoginVerify ([FromBody] string loginName ){}
At the same time, if the front-end call is still in the previous format
$. Post (
'.../Api/User/UserVerify ',
{LoginName: "admin "},
Function (json ){
Alert (json );
});
The following situation occurs: The jump can be normal, but the corresponding transmitted value cannot be obtained. Because the Web API requires the [FromBody] parameter to be passed by the request, it must have a specific format before it can be obtained correctly. This specific format is not common key = value pairs. The Web API Model binder wants to find the value without a key name in [FromBody], that is, it is not key = value, but = value.
Therefore, we will modify the call parameters to the following form:
Note that the service must be regenerated at this time.
3. Post requests with two or more parameters
[FromBody] only one modified parameter can be. We need to encapsulate multiple parameters passed.
Here, we can encapsulate loginName and passWord into a User class.
Background method required
[HttpPost, ActionName ("UserVerify")]
Public string LoginVerify ([FromBody] UserExEntity user)
{
Try
{
Return "name" + user. loginName + "passWord" + user. passWord;
}
Catch
{
Return null;
}
}
Frontend call required
At this point, we can see that the Form Data format is key = value & key = value. We usually use a lot of json format.