对于传递电子邮件地址,我使用带有POST的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) { ... }
这就是Fiddler所说的:
POST http://localhost:52498/api/Search/UserByEmail HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json;charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:52498/#
Accept-Language: de-DE
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Host: localhost:52498
Content-Length: 35
DNT: 1
Connection: Keep-Alive
Pragma: no-cache
{"emailAddress":"mail@example.com"}
为什么emailAddress参数始终为null?
答案 0 :(得分:1)
// 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 });
}
使用formModel并在类上放置一个serializable属性,它将序列化 你的javascript自动转换成C#等价物。而且您不需要使用Json-stringify。
注意删除// contentType:“application / json; charset = utf-8”, 来自ajax方法的声明。我其实从未使用过它。
答案 1 :(得分:0)
我认为JSON.stringify
可能是你的问题。 MVC将为您处理参数的序列化/反序列化,将其更改为:
data: { emailAddress: userEmail }
答案 2 :(得分:0)
将原始ajax调用中的data属性修改为
data: '"' + userEmail + '"',
让某些Web API调用工作有时会有点棘手