Asp.net
在每個控制器的 ASP.NET WebAPI 上強制使用 CamelCase
在 ASP.NET WebAPI 中,我知道您可以在 global.aspx 中使用CamelCasePropertyNamesContractResolver()將預設的 json 格式化程序設置為使用駝峰式大小寫,這將強制所有 json 序列化為駝峰式大小寫。
但是,我需要能夠在“每個控制器”實例上設置它,而不是全域解決方案。
這可能嗎?
感謝@KiranChalla,我比我想像的更容易做到這一點。
這是我創建的非常簡單的類:
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); } }然後只需將屬性添加到您想要 CamelCase 的任何 Controller 類。
[CamelCaseControllerConfig]