我的WebAPI应用程序中有一个模型,用.NET 4.0编写,含有一个System.Net.Mime.ContentType类型的属性,如下所示:
[Serializable]
public class FileData
{private ContentType contentType;private long size;private string name;public ContentType ContentType{get { return contentType; }set { contentType = value; } }.../* same getter/setter logic for the other fields */
}
该模型的定义位于我的Web项目的另一个程序集中.
所以,客户端发给我一个JSON消息,我需要转换为这个类:
{"contentType": "image/png","size": 12345,"name": "avatar.png"
}
为了告诉Json.NET如何转换ContentType,我注册了一个自定义的JsonConverter:
JsonFormatter.SerializerSettings.Converters.Add(new ContentTypeJsonConverter());
在上面的代码中,我指的是WebApi应用程序的全局JsonFormatter对象.
因此,当客户端向我发送JSON时,我希望控制器能够正确地解析消息.
不幸的是,它失败并出现错误:
“Could not cast or convert from System.String to System.Net.Mime.ContentType.”
我知道我可以通过将以下代码添加到我的FileData类来解决这个问题:
public class FileData
{...[JsonConverter(typeof(ContentTypeJsonConverter))]public ContentType ContentType { /* Getter and Setter */ }
}
但问题是我不能在FileData类型所在的程序集中向JSON.NET引入依赖项.
有没有办法在不改变FileData类的情况下触发contentType成员的正确反序列化?
除了以上我还尝试了Brian Rogers建议:
JsonFormatter.SerializerSettings.ContractResolver = new CustomResolver();
使用以下CustomResolver实现:
class CustomResolver : DefaultContractResolver
{protected override JsonContract CreateContract(Type objectType){var contract = base.CreateContract(objectType);if (objectType == typeof(ContentType)){contract.Converter = new ContentTypeJsonConverter();}return contract;}
}
结果仍然相同.
最佳答案 以下适用于我(Web API 2).
模型:
[Serializable]
public class FileData
{private ContentType contentType;public ContentType ContentType{get { return contentType; }set { contentType = value; }}
}
自定义JSON转换器:
public class ContentTypeJsonConverter : JsonConverter
{public override bool CanConvert(Type objectType){return objectType == typeof(ContentType);}public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){return new ContentType((string)reader.Value);}public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer){writer.WriteValue(((ContentType)value).ToString());}
}
转换器注册(WebApiConfig.cs):
public static void Register(HttpConfiguration config)
{...config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new ContentTypeJsonConverter());
}
控制器:
public class TestController : ApiController
{public IHttpActionResult Post(FileData data){return this.Ok(data);}
}
请求:
POST /api/test HTTP/1.1
Content-Type: application/json
Host: localhost:48278
Content-Length: 36{"contentType": "image/png"
}
响应:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?ZDpcd29ya1xUb0REXGFwaVx0ZXN0?=
X-Powered-By: ASP.NET
Date: Mon, 25 Jul 2016 07:06:02 GMT
Content-Length: 27{"contentType":"image/png"}
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。