Web API网站上的POST方法接收到null json

时间:2019-02-02 18:55:00

标签: python post asp.net-web-api attributes

我有一个python客户端,想通过邮政网页API调用从DB获得用户的详细信息,但是当我调试我的Web API,我传递给POST方法的参数为null。从蟒蛇网站我传递词典序列化到JSON和web.api应该接受它作为一个自定义对象调用证书并用它来从数据库获取数据并寄回。

我用C#客户端和everythink工作得很好,JSON看起来完全一样。 我还尝试过restlet客户端,当我从python复制粘贴正文值时,效果很好。

Python:

def CredentialsCheck(self,credentials):
    credentialsDictionary = { "Email": credentials.email, "Password": 
    credentials.password}
    data = json.dumps(credentialsDictionary)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

    request = requests.post(self.url,json = data,headers = headers)
    response = request.json()
    print(response)

creds = UserCredentials("n","s")

api = WebApiDataHandler()
api.CredentialsCheck(creds)

显然还有 init (自己):我在其中设置网址

C#UI: - 这一个工作正常

    public CalendarUser CredentialsCheck(CalendarUserCredentials credentials)
        {
            wc.Headers.Add("Content-Type", "application/json");
            wc.Headers.Add("Data-Type", "application/json");
            string userJson = serializer.Serialize(credentials);
            string test = wc.BaseAddress + "GetUser" + userJson;
            CalendarUser loggedInUser = serializer.Deserialize<CalendarUser> 
    (wc.UploadString(wc.BaseAddress + "GetUser", "Post", userJson));
            if (loggedInUser.Name != "" && loggedInUser.Surname != "" && 
    loggedInUser.Name != null && loggedInUser.Surname != null)
                return loggedInUser;
            else
                throw new ArgumentException("Incorrect log in details.");
        }

C#网页API控制器:

[HttpPost]
public CalendarUser GetUser([FromBody]CalendarUserCredentials credentials) //when i put breakpoint here it fires but value of CalendarUserCredentials is null
{
     CalendarUser user = new CalendarUser();
     dataHandler.CredentialsCheck(credentials, out user);
     return user;
}

我希望Web api GetUser方法将接收CalendarUserCredentials,其中电子邮件的值为“ n”,密码的值为“ s”

1 个答案:

答案 0 :(得分:0)

我通过将CalendarUserCredentials更改为字符串然后反序列化此字符串来解决了该问题,尽管如果有人有更好的解决方案,请与我分享:)

JavaScriptSerializer serializer = new JavaScriptSerializer();

[HttpPost]
        public CalendarUser GetUser([FromBody]string json)
        {
            CalendarUserCredentials credentials = serializer.Deserialize<CalendarUserCredentials>(json);
            CalendarUser user = new CalendarUser();
            dataHandler.CredentialsCheck(credentials, out user);
            return user;
        }

我想了解为什么它接受来自C#,并将其转换JSON到正确CalendarUserCredentials但如果我在Python发送相同的JSON它只能看到空O.o