ASP.NET MVC中强制使用SnakeCaseNamingStrategy无效问题求助
解决SnakeCaseNamingStrategy反序列化映射失败问题
针对你遇到的发送confirm_password时ConfirmPassword始终为null的问题,可通过以下步骤排查修复:
1. 调整全局配置的位置与参数
将JSON序列化配置移至WebApiConfig.Register方法中(而非Global.asax),避免配置顺序冲突导致设置未生效,同时显式启用SnakeCaseNamingStrategy的相关参数:
public static void Register(HttpConfiguration config) { // 其他Web API路由/配置代码... config.MapHttpAttributeRoutes(); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy( processDictionaryKeys: true, overrideSpecifiedNames: true) }; }
原Global.asax中在GlobalConfiguration.Configure之后修改配置,可能被WebApiConfig内的默认设置覆盖,移至WebApiConfig内可确保配置正确注入请求管道。
2. 确保请求使用JSON格式
若你发送的是表单数据(application/x-www-form-urlencoded或multipart/form-data),JsonFormatter的命名策略配置不会生效——这类请求由FormDataModelBinder处理,而非JSON序列化器。
需将请求的Content-Type设为application/json,并以JSON字符串传递数据:
{ "email": "test@example.com", "password": "123456", "confirm_password": "123456" }
3. 表单数据场景的兼容方案
若必须支持表单数据的蛇形命名映射,可手动给属性添加[JsonProperty]特性指定映射名称:
[JsonObject(NamingStrategyType = typeof(Newtonsoft.Json.Serialization.SnakeCaseNamingStrategy))] public class RegisterBindingModel { // 其他属性代码... [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] [JsonProperty("confirm_password")] public string ConfirmPassword { get; set; } }
4. 版本兼容性检查
确认项目中所有引用的Newtonsoft.Json版本均为13.0.0.0,避免版本冲突导致命名策略失效。
内容的提问来源于stack exchange,提问作者Hooman Limouee
相关产品推荐
相关产品推荐

