Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

json - Force CamelCase on ASP.NET WebAPI Per Controller

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.

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...