我正在使用ASP.NET web api。为了为端点返回的属性提供驼峰大小写的支持,我添加了以下代码:
//Support camel casing
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
这工作正常,但我想为其中一个端点添加一个例外。这将确保从该终点返回数据时,属性不是骆驼。如何添加此例外或单个端点?
答案 0 :(得分:1)
如果您应用全局camel case configuration
,则无法控制
AFAK实现此目的的唯一方法是使用ActionFilterAttribute
类似于以下内容
public class CamelCasingFilterAttribute:ActionFilterAttribute
{
private JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();
public CamelCasingFilterAttribute()
{
_camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
if (content != null)
{
if (content.Formatter is JsonMediaTypeFormatter)
{
actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, _camelCasingFormatter);
}
}
}
}
public class ValuesController : ApiController
{
// GET api/values
[CamelCasingFilter]
public IEnumerable<Test> Get()
{
return new Test[] {new Test() {Prop1 = "123", Prop2 = "3ERr"}, new Test() {Prop1 = "123", Prop2 = "3ERr"}};
}
// GET api/values/5
public Test Get(int id)
{
return new Test() {Prop1 = "123", Prop2 = "3ERr"};
}
}
public class Test
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
如果您尝试调用第一个操作,则答案将如下所示
[{"prop1":"123","prop2":"3ERr"},{"prop1":"123","prop2":"3ERr"}]
并且对于没有过滤器的第二个动作,你会得到类似这样的东西
{
"prop1": "123",
"prop2": "3ERr"
}
注意如果您希望在整个控制器上轻松控制camelCase,请尝试将您希望它的操作发送回控制器中的非CamelCase,但是,如果需要,其余的在控制器级别应用此过滤器。 更多您应该删除GlobalConfiguration以获取此