我在ASP.Net中有一个JSON2.0项目,在该项目中,我实现了一个自定义DefaultContractResolver,以便能够控制如何使用JSON.Net将实体序列化为JSON;但是,我不确定如何告诉框架使用自定义实现。我还想知道是否可以将ContractResolver更改为特定的控制器/操作。
谢谢!
这是因为默认情况下,webAPI控制器序列化响应,因此我想更改以覆盖该行为.走这条路对吗?
发布于 2014-07-04 21:20:54
我只是经历了自己想出来的痛苦,我需要一个能按要求工作的方法。您可以使用这种方法,只需返回相同的媒体格式化程序。我发现在GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver上设置格式化程序对于每个请求的需求来说有点不可靠,尽管我尝试在该类的一个实例中处理每个请求的需求。不过,您可以尝试在ContractResolver代码中的某个地方设置您的App_Start实例。
最后,我创建了一个自定义JsonMediaTypeFormatter,它检查请求是否有配置的ContractResolver,您只需返回一个和相同的解析器:
public class DynamicJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
// shown is getting the current formatter, but you can return an instance you prefer
var formatter = base.GetPerRequestFormatterInstance(type, request, mediaType) as JsonMediaTypeFormatter;
// Here I had more code to get the resolver based on request, skipped
((JsonMediaTypeFormatter)formatter).SerializerSettings.ContractResolver = <YourContractResolverInstance>;
return formatter;
}
}我想您已经知道这部分内容了,但是您的合同解析器可以覆盖“`CreateProperties”,并由您自己的逻辑决定哪些json属性将出现,它们将使用哪些名称(为了其他读者的完整性和利益而添加):
public class DynamicContractResolver : DefaultContractResolver
{
...
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization){
...
}发布于 2014-07-04 16:45:50
最后,我更改了方法的返回类型,如下所示:
我们有一个简单的Foo类:
public class Foo
{
public string Bar {get; set;}
}使用ASP 2.0,用于GET的脚手架控制器方法如下所示:
// GET api/Foo
public IQueryable<Foo> GetFoos()
{
var foos = GetAListOfFoosFromSomewhere() //returns an IQueryable<Foo>
return Foos
}注意,该框架自动地将Foos序列化为JSON。
所以我所做的就是把这个方法改为:
// GET api/Foo
public HttpResponseMessage GetFoos()
{
var foos = GetAListOfFoosFromSomewhere(); //returns an IQueryable<Foo>
var settings = new JsonSerializerSettings()
{
ContractResolver= new MyCustomContractResolver(), //Put your custom implementation here
//Also set up ReferenceLoopHandling as appropiate
};
var jsoncontent = JsonConvert.SerializeObject(foos, settings);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(jsoncontent, Encoding.UTF8, "application/json")
};
return response;
}在我的解决方案中,我添加了一个convience方法来创建HttpResponseMessage,所以它看起来有点像这样:
public HttpResponseMessage GetFoos()
{
var foos = GetAListOfFoosFromSomewhere() //returns an IQueryable<Foo>
return CreateResponse(foos);
}mercury2269的这篇文章真的很有帮助。
https://stackoverflow.com/questions/24543385
复制相似问题