强制CamelCase在ASP.NET WebAPI每个控制器

在ASP.NET WebAPI中,我知道您可以设置默认的json格式化程序以使用global.aspx中使用 CamelCasePropertyNamesContractResolver()的骆驼案例,这将强制所有json序列化为骆驼案例。

但是,我需要将其设置为“Per Controller”实例,而不是Global解决方案。

这可能吗?

解决方法

感谢@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]

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....