问题描述
我有一个MVC 4 Web API.通常,我希望响应返回所有属性,但是有一个地方我只想返回非空值.我可以通过在全局文件中设置 GlobalConfiguration.Configuration
实例的 Formatters.JsonFormatter.SerializerSettings.NullValueHandling
的JsonSerializerSettings来设置这两种行为,但是我想根据两者使用响应.有没有一种简单的方法可以从API控制器操作中配置请求范围?
I have an MVC 4 Web API. Usually I want responses to return all properties, but there is one place I only want to return only non-null values. I can setup either behavior by setting the JsonSerializerSettings of the Formatters.JsonFormatter.SerializerSettings.NullValueHandling
of the GlobalConfiguration.Configuration
instance in the global file but I want to use both depending on the response. Is there an easy way to configure the request scope from within an API controller action?
推荐答案
通过更改控制器操作以返回HttpResponseMessage,您可以更好地控制特定操作的内容返回方式.例如
By changing your controller action to return HttpResponseMessage you can get more control over how your content is returned for a particular action. e.g.
public HttpResponseMessage Get() {
var foo = new Foo();
var objectContent = new ObjectContent<Foo>(foo, new JsonFormatter()
{SerializerSettings.NullValueHandling = ???})
return new HttpResponseMessage() {Content = objectContent};
}
这篇关于设置每个响应的JsonSerializerSettings吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!