添加Serializable属性时,为什么值为null?

时间:2016-07-13 09:06:40

标签: c# .net serialization asp.net-web-api asp.net-web-api2

我有一个WebAPI 2,我正在尝试Post其中一种方法的模型。

我的完整Postman请求如下所示:

POST http://localhost:58900/api/v1/test HTTP/1.1
Host: localhost:58900
Connection: keep-alive
Content-Length: 295
Authorization: Bearer <<my bearer token>>
Postman-Token: 970cb0c1-3a8c-7a1e-763a-7dd916c035f3
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,sv;q=0.6,fr;q=0.4

{
    MyProperty: 'Test',
    MyGuid: '67345ac2-551e-d16e-b448-e697e369dea1'
}

我的控制器方法如下所示:

[HttpPost]
public IHttpActionResult Post([FromBody]MyModel myModel)
{
    //Doing stuff
}

一切都按预期工作但是当我将Serializable属性添加到我的模型时,所有值都变为空,如下:

[Serializable]
public class MyModel
{
    public string MyProperty { get; set; }
    public Guid MyGuid { get; set; }
}

[HttpPost]
public IHttpActionResult Post([FromBody]MyModel myModel)
{
    //myModel.MyProperty is null and myModel.MyGuid is {00000000-0000-0000-0000-000000000000}
}

我假设(?)这是因为Serialization属性告诉运行时使用二进制格式化程序而不是我的配置中指定的JsonFormatter - 但是,最好的方法是什么解决这个问题?

我首先需要Serialization属性的原因是允许deep copy个对象;

public static List<T> Clone<T>(this IEnumerable<T> list)
{
    var ms = new MemoryStream();
    var bf = new BinaryFormatter();
    bf.Serialize(ms, list);
    ms.Position = 0;
    return bf.Deserialize(ms) as List<T>;
}

1 个答案:

答案 0 :(得分:0)

发布我自己的替代答案;

一种可能的解决方案是更改深层复制方法Clone并使用JsonConvert来复制对象,这样就可以从模型类中删除[Serializable]属性;

public static T CloneJson<T>(this T source)
{
    if (ReferenceEquals(source, null)) return default(T);
    var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
    return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
}