【问题标题】:ASP.NET WEB API - CamelCasePropertyNamesContractResolver - force to ignore specific endpointsASP.NET WEB API - CamelCasePropertyNamesContractResolver - 强制忽略特定端点
【发布时间】:2017-07-13 21:40:15
【问题描述】:

我正在使用 ASP.NET web api。为了为端点返回的属性提供驼峰式支持,我添加了以下代码:

//Support camel casing
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

这工作正常,但我想为其中一个端点添加一个例外。这将确保从该端点返回数据时,属性不是驼峰式的。如何添加此异常或单个端点?

【问题讨论】:

    标签: c# asp.net asp.net-web-api asp.net-web-api2 asp.net-web-api-filters


    【解决方案1】:

    如果您正在应用全局 camel case configuration,则无法进行控制 AFAK 实现这一目标的唯一方法是使用ActionFilterAttribute 类似于以下内容

    public class CamelCasingFilterAttribute:ActionFilterAttribute
        {
            private JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();
    
            public CamelCasingFilterAttribute()
            {
                _camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }
    
            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
                if (content != null)
                {
                    if (content.Formatter is JsonMediaTypeFormatter)
                    {
                        actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, _camelCasingFormatter);
                    }
                }
            }
        }
    
    
    
      public class ValuesController : ApiController
        {
            // GET api/values
            [CamelCasingFilter]
            public IEnumerable<Test> Get()
            {
                return new Test[] {new Test() {Prop1 = "123", Prop2 = "3ERr"}, new Test() {Prop1 = "123", Prop2 = "3ERr"}};  
            }
    
            // GET api/values/5
    
            public Test Get(int id)
            {
    
                return new Test() {Prop1 = "123", Prop2 = "3ERr"};  
            }
        }
    
        public class Test
        {
            public string Prop1 { get; set; }
            public string Prop2 { get; set; }
        }
    

    如果您尝试调用第一个操作,答案将如下所示

    [{"prop1":"123","prop2":"3ERr"},{"prop1":"123","prop2":"3ERr"}]
    

    如果没有过滤器,第二个操作会得到类似的结果

    {
        "prop1": "123",
        "prop2": "3ERr"
    }
    

    注意如果您想在整个控制器上轻松控制 camelCase,请尝试将您希望它在控制器中的非 CamelCase 中发送回答案的操作分开,但是,对于如果您愿意,其余的在控制器级别上应用此过滤器。 更多你应该删除 GlobalConfiguration 来获得这个

    【讨论】:

    • +1。谢谢或快速回复。我知道这个选项。但我不想删除全局设置,然后在每个端点上添加过滤器属性,除非我真的必须这样做。我会再等一段时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2018-10-01
    • 2011-03-16
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多