Asp.net MVC 和web api 的action 在获取从前台传入的数据是有很大不同

前台使用ajax的方式向后台发起post的请求 Content-Type:application/json

使用以下json对象

{
"user":
{
"Username":"xxx",
"Password":"xxxx"
}
}
  {
"Username":"xxx",
"Password":"xxx"
}
        public string Login(User user)
{
try
{
Sign.Login(user);
}
catch (LoginException e)
{
return e.Message;
}
//保存登陆状态
FormsAuthentication.SetAuthCookie(user.Username, true);
return "success";
}

在mvc中可以使用这两种格式的json均能获取到的user的username,password,

而在webapi中使用第一种获取到user的username,password为null,第二种可以获取到user的username,password。

在mvc中

        public ActionResult Test(int a, int b, int c)
{
return View();
}

这个aciton可以传一个这样的json

{
"a":1,
"b":2,
"c":3
}

而在webapi中使用这种参数,会提示找不到配置的action,或许webapi在除了路由中定义的id(使用url参数传入)之外,只能定义引用类型的参数,并通过

  {
"Username":"xxx",
"Password":"xxx"
}

这种格式的json传入才能接收。

05-07 15:16
查看更多