Web API的参数

先声明:我的路由模板是加了action的 : routeTemplate: "api/{controller}/{action}/{id}",

Get请求:如果用模型对象来接收数据,则必须在模型对象类前标注[FromUri]

namespace WebApi.Controllers
{
    public class Login
    {
        public string userName { get; set; }
        public string password { get; set; }
    }
    public class HomeController : ApiController
    {
        //api/Home/Get?userName=admin&password=123456
        public bool Get(string userName, string password)
        {
            return (userName == "admin" && password == "123456");
        }

        //api/Home/GetLogin?userName=admin&password=123456  
        //Get请求:如果以模型的形式来接收数据就必须在模型类前面加[FromUri]
        public bool Get([FromUri]Login value)
        {
            return (value.userName == "admin" && value.password == "123456");
        }
    }  
}

Post请求

Post方法的参数,如果提交的请求体需要是name=lily&age=25这样的格式。如果用string Add(string name, int age)这种普通参数会有很多的坑(参考《C#进阶系列——WebApi 接口参数不再困惑:传参详解》),所以不要用。都用模型对象。

例如:public string Add(Person model)

也可以参数标注[FromBody]:public string Add([FromBody]Person model)。(只能有一个参数标注FromBody)。

缺点是:如果参数很少,每次都要写一个类,特别麻烦。

WebApi项目

namespace WebApi.Controllers
{
    public class Person
    {
        public string name { get; set; }
        public int age { get; set; }
    }
    public class HomeController : ApiController
    {
        [HttpPost]
        public bool Add(Person model) //或者写成这样: public bool Add([FromUri]Person model)
        {
            return (model.name == "admin" && model.age < 25);
        }
    }
}

在WebApi中新增一个html静态页面,在里面写js请求(经过测试,可以参数可以正常获取到值)

<script type="text/javascript">
    $(function () {
        AddItem();
    })  

    function AddItem() { //如果是Post传递参数,建议使用JSON.stringify({ name: "admin",age:21 })这种方式传值
        $.ajax({
            url: "http://localhost:14483/api/Home/Add",
            type: "Post",
            data: JSON.stringify({ name: "张三", age: 21 }),
            contentType: "application/json; charset=utf-8", //一定要加上这个
            dataType: "json",
            success: function (data, textStatus) {
                alert(data);
            }
        });
    }     
</script>

MVC项目 (经过测试,在MVC项目中用HttpClient请求WebApi中的Add方法,参数可以正常接收数据)

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        public async Task<ActionResult> Index()
        {
            HttpClient hc = new HttpClient();

            Dictionary<string, string> kv = new Dictionary<string, string>();
            kv["name"] = "admin";  
            kv["age"] = "26";  

            FormUrlEncodedContent content = new FormUrlEncodedContent(kv);
            var task = await hc.PostAsync("http://localhost:14483/api/Home/Add", content);
            var result = await task.Content.ReadAsStringAsync();
            return View();
        }
    }
}


猜你喜欢

转载自blog.csdn.net/Fanbin168/article/details/80673289
今日推荐