如何阅读JSON对象的WebAPI [英] How to read JSON object to WebAPI

查看:142
本文介绍了如何阅读JSON对象的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查了一些类似的问题,但没有答案似乎适合(或哑下来足以让我)。所以,我有一个非常简单的WebAPI,以检查是否有电子邮件用户数据库存在。

I've checked a few similar questions, but none of the answers seem to fit (or dumb it down enough for me). So, I have a really simple WebAPI to check if user with an email exists in DB.

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:

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 ?结果
修改结果
我不能通过电子邮件地址作为一个字符串,因为逗号(S)搞乱了路由。结果
AJAX调用工作正常,该对象被发送到的WebAPI。问题是我无法分析对象code的后面。

Now clearly, this doesn't work. The ajax call works fine, but how do I parse the json object to the WebAPI to be able to call it like id.email?
EDIT
I can't pass the email address as a string, because the comma(s) mess up the routing.
The ajax call works fine, the object is sent to the WebAPI. The problem is I can't parse the object in code behind.

推荐答案

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

Problem: Your current implementation are sending the email as an entity on a GET request. This is a problem because GET requests does not carry an entity HTTP/1.1 Methods Solution: Change the request to a POST

现在,因为你是POST'ing从客户端的电子邮件到你的API,你必须API实现改为POST:

Now because you are POST'ing the email from your client to your api, you have to change the API implementation to POST:

public bool Post(UserResponse id)


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

public bool Post([FromBody] UserResponse id)

如果你这样做(你还没有覆盖默认的模型粘合剂),你必须标注模型,如:

If you do this (and you have not yet overridden the default model binder), you have to annotate your model like:

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

我想这是所有 - 希望工程:)

I think that is all - hope it works :)

这篇关于如何阅读JSON对象的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆