gpt4 book ai didi

Asp.net POST 参数始终为空

转载 作者:行者123 更新时间:2023-12-01 01:34:26 24 4
gpt4 key购买 nike

为了传递电子邮件地址,我使用 Ajax 并以 POST 作为类型。

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

Controller :

[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 参数始终为空?

最佳答案

 // 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 并在类上放置一个可序列化的属性,它将序列化您的 javascript 自动转换为 C# 等效项。而且您不需要使用 Json-stringify。

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

关于Asp.net POST 参数始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19132385/

24 4 0
文章推荐: svn - 撤消 svn 变更集 1276-1284 和 1286-1294
文章推荐: javascript - 等待时循环替换
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com