理解中WebAPI的属性和相关操作 FormBody和 FormUri等(WebAPI 二)

时间:2022-07-03 23:37:14

1.FromUri使用

将数据通过url方式传递。我们需要在webapi方法标明,这个参数只接受url中参数的值,

 $("#Save").click(function () {
$.ajax({
url: 'http://localhost:21162/api/person/?str1=1&str2=3',
type: 'Get',
dataType: 'json',
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});

在参数比较少情况下、或者Url长度小于256的情况下。可以考虑使用FromUri, 部分游览器会现在url大小,在这种情况下我们就要使用FromBody

2.FromBody

将数据通过post data方式方式传递。我们需要在webapi方法标明接受data参数,传递json参数


        $("#Save").click(function () {
$.ajax({
url: 'http://localhost:21162/api/person/',
type: 'Get',
dataType: 'json',
data: { "str1": "1", "str2": "2" },
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});

3.ActionName使用,通过制定Action来调用方法

        [ActionName("GetAllPerson")]
public IEnumerable<Person> GetAllPerson([FromUri] string str1, [FromUri] string str2)
{
return new List<Person>() {
new Person() {ID="1", Name="李鸿章ALL",Age=15},
new Person() {ID="2", Name="杨玉红ALL",Age=15} };
}
      $("#Save").click(function () {
$.ajax({
url: 'http://localhost:21162/api/person/GetAllPerson?str1=1&str2=3',
type: 'Get',
dataType: 'json',
//data: { "str1": "1", "str2": "2" },
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});

4.NonAction  表示不被外部应用程序调用

5. [AcceptVerbs("GET","POST")]

        [ActionName("GetAllPerson")]  //指定ActionName
[NonAction] //不被外部应用程序调用
[AcceptVerbs("GET","POST")] //表示既可以Get请求,又可以Post请求
public IEnumerable<Person> GetAllPerson([FromUri] string str1, [FromUri] string str2)
{
return new List<Person>() {
new Person() {ID="1", Name="李鸿章ALL",Age=15},
new Person() {ID="2", Name="杨玉红ALL",Age=15} };
}