如何为通过FromUrl绑定的C#模型属性设置自定义查询字符串名称
问题根因
JsonProperty特性仅服务于JSON格式请求体的序列化/反序列化流程,QueryString走ASP.NET独立的模型绑定逻辑,不会读取JsonProperty的配置,因此你写的映射规则无法生效。
解决方案
分不同框架版本适配:
ASP.NET Core
直接在属性上添加[FromQuery]特性,通过Name参数指定QueryString对应的键名即可:
public class FormatDatabaseRequest { [FromQuery(Name = "_type")] public string Type { get; set; } [FromQuery(Name = "awef_flag")] public string AwefFlag { get; set; } } // Controller 代码 [HttpPost] public async Task<IActionResult> FormatDatabaseAsync([FromQuery] FormatDatabaseRequest request) { // 你的业务逻辑 }
ASP.NET Framework(使用[FromUri]的旧版本)
原生[FromUri]不支持属性级自定义键名,需要自定义模型绑定实现:
- 定义映射特性
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class QueryBindKeyAttribute : Attribute { public string KeyName { get; } public QueryBindKeyAttribute(string keyName) => KeyName = keyName; }
- 实现自定义模型绑定器
public class CustomQueryModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var model = Activator.CreateInstance(bindingContext.ModelType); var properties = bindingContext.ModelType.GetProperties(); foreach (var prop in properties) { var bindKey = prop.GetCustomAttribute<QueryBindKeyAttribute>()?.KeyName ?? prop.Name; var valueResult = bindingContext.ValueProvider.GetValue(bindKey); if (valueResult == null) continue; var convertedValue = Convert.ChangeType(valueResult.AttemptedValue, prop.PropertyType); prop.SetValue(model, convertedValue); } bindingContext.Model = model; return true; } }
- 给模型类标记特性
[ModelBinder(typeof(CustomQueryModelBinder))] public class FormatDatabaseRequest { [QueryBindKey("_type")] public string Type { get; set; } [QueryBindKey("awef_flag")] public string AwefFlag { get; set; } }
配置完成后原有Controller的[FromUri]接收逻辑无需改动,即可正确匹配自定义命名的QueryString参数。
内容的提问来源于stack exchange,提问作者Vijay Nirmal
相关产品推荐
相关产品推荐

