力驼峰上的ASP.NET的WebAPI每个控制器 [英] Force CamelCase on ASP.NET WebAPI Per Controller
问题描述
在ASP.NET的WebAPI,我知道你可以设置默认的JSON格式使用使用骆驼情况下<一个href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing\">CamelCasePropertyNamesContractResolver()在global.aspx这将迫使所有的JSON序列化骆驼情况。
In ASP.NET WebAPI, I know you can set the default json formatter to use camel case using CamelCasePropertyNamesContractResolver() in the global.aspx which will force ALL json serialization to camel case.
不过,我需要能够将其放置在每个控制器实例,而不是一个全球的解决方案。
However, I need to be able to set it on a "Per Controller" instance, instead of a Global solution.
这可能吗?
推荐答案
感谢@KiranChalla我之所以能够取得比我想象的更容易些。
Thanks to @KiranChalla I was able to achieve this easier than I thought.
下面是我创造了pretty简单的类:
Here is the pretty simple class I created:
using System;
using System.Linq;
using System.Web.Http.Controllers;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Serialization;
public class CamelCaseControllerConfigAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
var formatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
controllerSettings.Formatters.Remove(formatter);
formatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()}
};
controllerSettings.Formatters.Add(formatter);
}
}
然后,只需将该属性添加到您想要的任何驼峰Controller类。
Then just add the attribute to any Controller class you want CamelCase.
[CamelCaseControllerConfig]
这篇关于力驼峰上的ASP.NET的WebAPI每个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!