Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net POST参数始终为空_Asp.net_Jquery_Asp.net Mvc 4 - Fatal编程技术网

Asp.net POST参数始终为空

Asp.net POST参数始终为空,asp.net,jquery,asp.net-mvc-4,Asp.net,Jquery,Asp.net Mvc 4,为了传递电子邮件地址,我使用了带有POST as类型的ajax $.ajax({ url: "api/Search/UserByEmail", type: "POST", data: JSON.stringify({ emailAddress: userEmail }), contentType: "application/json;charset=utf-8", dataType: "json", success: function (data)

为了传递电子邮件地址,我使用了带有POST as类型的ajax

$.ajax({
    url: "api/Search/UserByEmail",
    type: "POST",
    data: JSON.stringify({ emailAddress: userEmail }),
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (data) { ... }
});
控制器:

[HttpPost]
public IEnumerable<Object> UserByEmail([FromBody] string emailAddress) { ... }

为什么emailAddress参数总是空的?

我认为
JSON.stringify
可能是您的问题。MVC将为您处理参数的序列化/反序列化,将其更改为:

data: { emailAddress: userEmail }
使用formModel并在类上放置可序列化属性,它将序列化 您的javascript会自动转换为C#等价物。您不需要使用Json stringify

注意a删除了//contentType:“application/json;charset=utf-8”,
来自ajax方法的声明。实际上我从来没有用过

修改对的原始ajax调用中的数据属性

data: '"' + userEmail + '"',

让这些Web API调用发挥作用有时会有点棘手

“你不需要使用JSON.stringify”-如果你想以JSON的形式传递数据,你可以这样做…不,如果你有一个可序列化的类作为参数进入你的方法,它会自动将javascript对象转换为C。我自己也用过很多,很好!!是的,尽管你不再使用JSON,但我要说的是——数据被转换成查询字符串并附加到URL。是的,但它仍然是一个HTTP帖子!是的,但正如我所说,您不再从客户端发布JSON,因此
application/JSON
也必须更改为
application/x-www-form-urlencoded
。这在我看来很好,您是否测试过使用Fiddler构建请求并手动发布?最有可能的问题是JSON数据,但从这里我看不出它有什么问题。您也可以尝试删除
[FromBody]
属性。当我取出
[FromBody]
时,我的方法甚至没有被调用。以下是路由:
config.Routes.maphttprote(名称:“UserByEmailRoute”,路由模板:“api/Search/UserByEmail”,默认值:new{controller=“Search”,action=“UserByEmail”})
这可能是有道理的,如果你发布
api/Search/UserByEmail/emailAddress,你可能会在Fiddler中发布
=mail@example.com
身体在起作用吗?是的,它起作用了。谢谢。@user2558051另外,去掉
FromBody
属性,我很确定你不需要它(我从来没有听说过!)@mattyommo你通常需要WebAPI的
[FromBody]
属性……不过,我觉得这里可能也有问题(见我的评论)。
 // JS - jQuery 
 $.ajax({
        url: "/Home/UserByEmail",
        type: "POST",
        data: { emailAddress: "joe@gmail.com" },
        dataType: "json",
        success: function (data) { if(data != null) { alert(data.toString()); } }
    });



  [Serializable]
  public class EmailFormModel {
     public string emailAddress { get; set; }
  }

    [HttpPost]
    public JsonResult UserByEmail(EmailFormModel emailFormModel)
    {
        bool ok = emailFormModel.emailAddress != null;
        return Json(new { ok }); 
    }
data: '"' + userEmail + '"',