Force CamelCase on ASP.NET WebAPI Per Controller

后端 未结 4 766
隐瞒了意图╮
隐瞒了意图╮ 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:49

    This Stack Overflow answer should be helpful. It shows you how to create an ActionFilter which can be applied to any action where you wish to use CamelCasing.

    0 讨论(0)
  • 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<JsonMediaTypeFormatter>().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]
    
    0 讨论(0)
  • 2020-11-29 07:53

    Yes, it's possible...you can use IControllerConfiguration to define per-controller specific configuration..

    This is a sample which describes this scenario. You can quickly take a look at how this interface should be used over here(from the sample).

    0 讨论(0)
  • 2020-11-29 07:57

    I know this is pretty old, but I had a problem with the accepted answer because there were other necessary changes to the formatter that were no longer present after removing and re-adding. I did this by just modifying the existing formatter as shown in this Gist: https://gist.github.com/mauricedb/5356933.

    0 讨论(0)
提交回复
热议问题