CamelCasePropertyNamesContractResolver在MapHttpRoute之后无法正常工作 [英] CamelCasePropertyNamesContractResolver not Working after MapHttpRoute

查看:167
本文介绍了CamelCasePropertyNamesContractResolver在MapHttpRoute之后无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的.Net API项目中实现JSON camel大小写.在我的启动课程中,添加以下行:

I'm trying to implement JSON camel casing in my .Net API project. In my start up class I add the following lines:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = 
    new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

据我了解,这就是在所有路线上实施骆驼套的必要条件.但是,当我添加以下内容后,此方法将无法正常工作,响应将以Pascal Case的形式返回:

As I understand it this is what is required to implement camel casing on all routes. However when I add the following this fails to work, the responses come back as Pascal Case:

RouteTable.Routes.MapHttpRoute(
    "DefaultApi",
     "{controller}/{id}",
      new {id = RouteParameter.Optional}
);

当我删除上面的MapHttpRoute行并在控制器中使用Route属性时,骆驼套可以正常工作.

When I remove the above MapHttpRoute line and use Route attributes in the controllers instead camel casing works fine.

有人对这里发生的事情有任何想法吗?

Has anyone any idea as to what is happening here?

推荐答案

在回答之前,您首先应该了解,驼峰案例API响应优先于不会影响模型验证(我们将解决此问题)答案末尾有问题).

Before we answer, you should understand first that the camel case API response overriding will NOT affect the Model Validation (we will solve this problem at the end of answer).

您的问题:

您必须使用相同的 HttpConfiguration 变量,因此请尝试使用此变量

You have to use the same HttpConfiguration variable so try to use this instead

// config is an HttpConfiguration object

config.Routes.MapHttpRoute(
     name: "API Default",
     routeTemplate: "api/{controller}/{id}",
     defaults: new { id = RouteParameter.Optional });

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

用于模型验证:

您必须创建一个所有其他控制器都应继承的基本控制器,然后通过创建一个必须替代使用的新方法(ModelState是只读属性)来覆盖ModelStateDictionary,如下所示(1):

You have to create a base controller that all your other controllers should inherit from, then override the ModelStateDictionary by creating a new method that you have to use instead (ModelState is a read-only property) as below (1):

public class BaseApiController : ApiController
{
    public ModelStateDictionary ModelStateAsCamelCase()
    {
        var newModelStateDictionary = new ModelStateDictionary();

        foreach (var element in ModelState)
        {
            if (!string.IsNullOrWhiteSpace(element.Key))
            {
                var keys = element.Key.Split('.');
                List<string> camelKeys = new List<string>();
                foreach (var key in keys)
                {
                    camelKeys.Add(key.First().ToString().ToLowerInvariant() + key.Substring(1));
                }

                // You can (add a / change this) code if the returned key is not
                // composed from the ObjectName.Property, such as when it is 
                // composed from the property name

                var newKey = camelKeys.Aggregate((i, j) => i + "." + j);

                newModelStateDictionary.Add(newKey, element.Value);
            }
            else
                newModelStateDictionary.Add(element);
        }
        return newModelStateDictionary;
    }
}

此方法将编辑模型状态字典字符串键以符合骆驼约定

this method will edit the model state dictionary string key to comply the camel convention

现在在您的操作中,您可以使用此方法代替默认的ModelState

now inside your action, you can use this method instead of the default ModelState

......

if (!ModelState.IsValid)
    return BadRequest(ModelStateAsCamelCase());

......

1-我已经检查了许多解决modelState中的camelCase问题的答案,即使在.net核心中也没有,但没有提供默认配置解决方案.正如他们提到的那样,modelState不会受到我的答案第一部分中使用的默认配置的影响

1- I have checked many answer related to solve the camelCase problem in modelState even in .net core but non has provided a default config solution. as they mentioned that the modelState will not get affected by the default config used in the first part from my answer

这篇关于CamelCasePropertyNamesContractResolver在MapHttpRoute之后无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆