API未收到序列化对象的json

API未收到序列化对象的json

本文介绍了Web API未收到序列化对象的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端代码:

        public async Task<ActionResult> Login(UserLoginModel user)
    {
        UserModel data = new UserModel
        {
            Username = user.Username,
            Password = user.Password.GenerateHash()
        };

        var serializedData = JsonConvert.SerializeObject(data);

        var url = "http://localhost:55042/api/Login";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(serializedData);
            streamWriter.Flush();
            streamWriter.Close();
        }

        bool deserializedResult = false;
        using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
        {
            if (httpWebRequest.HaveResponse && response != null) {
                using (var streamReader = new StreamReader(response.GetResponseStream())) {
                    var result = streamReader.ReadToEnd();
                    deserializedResult = JsonConvert.DeserializeObject<bool>(result);
                }
            }
        }

        return deserializedResult ? View() : throw new NotImplementedException();
    }

Web API:

    [HttpPost]
    [Route("api/Login")]
    public IHttpActionResult ValidateLogin([FromBody]UserModel user)
    {
        var result = _service.FetchUser(user);

        return Json(result);
    }

UserModel

UserModel

[Serializable]
public class UserModel
{
    public int? ID { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }

    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public string Email { get; set; }

    public string NumberI { get; set; }

    public string NumberII { get; set; }

    public DateTime? CreateDate { get; set; }
}

即使我通过邮递员传递参数,也没有数据到达ValidateLogin.

No data arrives in ValidateLogin, even when I pass parameters with the postman.

我搜索了很多 ,根本没有找到解决方案,尝试了所有代码片段,理解了它们然后又回来了,依此类推,我被卡住了,怎么了?

I have searched a lot, found no solution at all, tried all the code snippets, understood them then came back and so on, I'm stuck, what is wrong?

推荐答案

解决方案1 ​​

只需从UserModel中删除[Serializable]属性,一切都会正常运行.

Just remove [Serializable] attribute from UserModel and everything will work fine.

解决方案2

在客户端上序列化数据时,像Web API一样使用json序列化行为

When serializing data on client use json serialization behavior as Web API does

var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        IgnoreSerializableAttribute = false
    }
});

现在Web API将正确反序列化传递的模型.

Now Web API will correctly deserialize passed model.

之所以发生这种情况,是因为从某个版本Json.NET开始考虑对象是否标记为Serializable.默认情况下,没有该属性的情况下,所有公共成员(属性和字段)都会被序列化.以下类的序列化

This happens because starting from some version Json.NET considers if object is marked as Serializable. By default without that attribute all public members (properties and fields) are serialized. Serialization of the following class

public class UserModel
{
    public string Username { get; set; }

    public string Password { get; set; }
}

给出以下结果

{
  "Username": "name",
  "Password": "pass"
}

但是,当通过[Serializable]属性标记类并且IgnoreSerializableAttribute设置为false时,所有私有字段和公共字段都将被序列化,结果如下所示:

But when class is marked by [Serializable] attribute and IgnoreSerializableAttribute setting is false all private and public fields are serialized and result is the following

{
  "<Username>k__BackingField": "name",
  "<Password>k__BackingField": "pass"
}

默认情况下,序列化程序忽略[Serializable]属性,但是在Web API中,IgnoreSerializableAttribute设置为false.因此,现在很容易看到为什么服务器无法在您的情况下正确反序列化给定模型.

By default serializer ignores [Serializable] attribute but in Web API the IgnoreSerializableAttribute is set to false. So now it's easy to see why server couldn't properly deserialize given model in your case.

这篇关于Web API未收到序列化对象的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:00