【发布时间】:2016-02-27 00:10:25
【问题描述】:
我检查了一些类似的问题,但似乎没有一个答案适合(或者对我来说已经足够愚蠢了)。所以,我有一个非常简单的 WebAPI 来检查数据库中是否存在带有电子邮件的用户。
AJAX:
var param = { "email": "ex.ample@email.com" };
$.ajax({
url: "/api/User/",
type: "GET",
data: JSON.stringify(param),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data == true) {
// notify user that email exists
}
else {
// not taken
}
}
});
WebAPI:
public bool Get(UserResponse id)
{
string email = id.email;
UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>();
ApplicationUserManager<ApplicationUser> manager = new ApplicationUserManager<ApplicationUser>(userStore);
ApplicationUser user = manager.FindByEmail(email);
if (user != null)
{
return true;
}
else
{
return false;
}
}
//helper class:
public class UserResponse
{
public string email { get; set; }
}
现在很明显,这是行不通的。 ajax 调用工作正常,但如何将 json 对象解析为 WebAPI 以便能够像 id.email 一样调用它?
编辑
我无法将电子邮件地址作为字符串传递,因为逗号会混淆路由。
ajax 调用工作正常,对象被发送到 WebAPI。问题是我无法解析后面代码中的对象。
【问题讨论】:
-
在您的 ajax 中将 GET 更改为 POST
-
为什么一定要张贴?我在示例中看到它,但我认为我正在发出 GET 请求..?
-
在这种情况下,您不需要将其作为帖子,但您需要更改一些内容。我将在下面发布答案。
标签: c# json ajax asp.net-web-api