Force CamelCase on ASP.NET WebAPI Per Controller

后端 未结 4 826
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 07:04

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 jso

4条回答
  •  广开言路
    2020-11-29 07:51

    Thanks to @KiranChalla I was able to achieve this easier than I thought.

    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().Single();
        controllerSettings.Formatters.Remove(formatter);
    
        formatter = new JsonMediaTypeFormatter
        {
          SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()}
        };
    
        controllerSettings.Formatters.Add(formatter);
    
      }
    }
    

    Then just add the attribute to any Controller class you want CamelCase.

    [CamelCaseControllerConfig]
    

提交回复
热议问题