One, GET request
1, no parameter get request, as usual to write Ajax requests, and no difference
$.ajax ({
URL: ' .../api/user/userverify,
Type: ' Get ',
Success:function (JSON) {
alert (JSON);
},
Error:function () {
Alert ("Error");
}
});
At this point, the background Code API code can directly public string userverify (){}, you need to add the HttpGet attribute on the action
2, get request 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");
}
});
At this point, the background API code can be public string loginverify (string loginname,string passWord) {}, you need to add the HttpGet attribute on the action
Second, POST request
1, non-parametric POST request
$.post (
' .../api/user/userverify ',
function (JSON) {
alert (JSON);
});
At this point, the background call needs to add the HttpPost attribute on the action, public string Loginverify () {}
2, a parameter of the POST request
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. That is to be written in the following form:
[Httppost,actionname ("Userverify")]
public string Loginverify ([frombody]string loginName) {}
At the same time, the foreground call if you still press the previous wording
$.post (
' .../api/user/userverify ',
{loginName: "admin"},
function (JSON) {
alert (JSON);
});
The following occurs: You can jump normally, but you cannot get the value of the corresponding transfer. Because the Web API requires the [frombody] parameter for the request to be passed, there must be a specific format in order to be properly fetched. 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.
So, let's change the invocation parameter to the following form:
When you need to be aware, be sure to regenerate the service at this time
3, POST request for two or more parameters
the [frombody] modifier can have only one parameter . We need to encapsulate the multiple parameters passed.
Here, we can encapsulate LoginName and PassWord as a user class
The background method requires
[Httppost,actionname ("Userverify")]
public string loginverify ([frombody]userexentity user)
{
Try
{
Return "name" + user.loginname+ "password" +user.password;
}
Catch
{
return null;
}
}
Foreground call required
At this point, we can see that the form data format is Key=value&key=value, we usually use a more general JSON format.
Summary of issues that occur in using AJAX to invoke Web Api methods