如何将JSON对象读取到WebAPI

我已经检查了一些类似的问题,但没有一个答案似乎适合(或者对我来说足够愚蠢)。 所以,我有一个非常简单的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 userStore = new UserStore(); ApplicationUserManager manager = new ApplicationUserManager(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。 问题是我无法在后面的代码中解析对象。

问题:您当前的实施是在GET请求上将电子邮件作为实体发送。 这是一个问题,因为GET请求不携带实体HTTP / 1.1方法解决方案:将请求更改为POST

现在因为您要将客户端的电子邮件发送到api,您必须将API实现更改为POST:

 public bool Post(UserResponse id) 

要确保您发布的实体绑定正确,您可以使用[FromBody]如:

 public bool Post([FromBody] UserResponse id) 

如果您这样做(并且尚未覆盖默认模型绑定器),则必须为您的模型添加注释,如:

 [DataContract] public class UserResponse { [DataMember] public string email { get; set; } } 

我认为这就是全部 – 希望它有效:)

将其更改为POST以发送您尝试通过请求正文发送的对象,或更改方法签名以接受电子邮件地址。

 var param = { "email": "ex.ample@email.com" }; $.ajax({ url: "/api/users/" + param.email, type: "GET", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if (data == true) { // notify user that email exists } else { // not taken } } }); [HttpGet, Route("api/users/{emailaddress}")] public bool Get(string emailaddress) { string email = emailaddress; UserStore userStore = new UserStore(); ApplicationUserManager manager = new ApplicationUserManager(userStore); ApplicationUser user = manager.FindByEmail(email); if (user != null) { return true; } else { return false; } } //helper class: public class UserResponse { public string email { get; set; } } 
 var dto = { Email: "ex.ample@email.com" }; $.ajax({ url: "/api/User/", type: "GET", data: dto, contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if (data == true) { // notify user that email exists } else { // not taken } } }); 

您可以在JavaScript中创建一个对象:

 var myData= { Email: "me@email.com" }; 

这将创建一个对象,匹配控制器所需的对象。

然后设置Ajax调用以将其作为data属性传递:

 $.ajax({ url: "/api/User/", type: "GET", data: myData, contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { if (data == true) { // notify user that email exists } else { // not taken } } }); 

我喜欢这种方法,因为您可以根据需要添加更多属性。 但是,如果您只传递电子邮件地址,则可能只想传递一个字符串。