如果您正在应用全局 AFAK,则无法进行控制camel case configuration
,实现此目的的唯一方法是使用 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 来得到这个