【问题标题】:How to read JSON object to WebAPI如何将 JSON 对象读取到 WebAPI
【发布时间】: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


【解决方案1】:

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

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

public bool Post(UserResponse id)

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

public bool Post([FromBody] UserResponse id)

如果你这样做(并且你还没有覆盖默认的模型绑定器),你必须像这样注释你的模型:

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

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

【讨论】:

  • 谢谢。这正是我所需要的。当你回答这个问题时,写了我自己的答案。我正在删除我自己的,因为这指出了所有相关的内容并回答了我的后续问题 =)
【解决方案2】:

要么将其更改为 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<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; }
}

【讨论】:

    【解决方案3】:
    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
            }             
        }                      
    });
    

    【讨论】:

      【解决方案4】:

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

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

      这将创建一个对象,与控制器预期的对象相匹配。

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

      $.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
              }             
          }                      
      });
      

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

      【讨论】:

      • 这正是我所做的。不工作。问题是如何在后面的代码中解析对象。我不能将它作为字符串传递,因为它包含一个或多个逗号,这会打乱路由。
      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 2012-07-13
      • 2015-03-08
      • 1970-01-01
      • 2020-11-25
      • 2019-08-12
      • 2016-11-05
      • 2016-04-01
      相关资源
      最近更新 更多