c# - 将模型值设置为小写的 ASP.NET Core 2.1 属性
问题描述
我想知道当我在控制器上收到模型时,是否有办法强制某些属性的值始终为小写或大写。最好以干净的方式,例如使用属性。
例子:
控制器:
[HttpPost]
public async Task<Model> Post(Model model)
{
//Here properties with the attribute [LowerCase] (Prop2 in this case) should be lowercase.
}
模型:
public class Model
{
public string Prop1 { get; set; }
[LowerCase]
public string Prop2 { get; set; }
}
我听说使用自定义ValidationAttribute更改值不是一件好事。还决定创建一个自定义DataBinder,但没有确切地找到我应该如何实现它,当尝试这样做时,我的控制器中刚刚收到null。
解决方案
替代解决方案: Fluent API:
modelBuilder.Entity<Model>()
.Property(x => x.Prop2)
.HasConversion(
p => p == null ? null : p.ToLower(),
dbValue => dbValue);
或者,封装在类本身中,使用带有支持字段的属性:
private string _prop2;
public string Prop2
{
get => _prop2;
set => value?.ToLower();
}
推荐阅读
- amazon-web-services - 无法使用 kubernetes-Jenkins 插件配置 kubernetes URL
- android - 将firestore,androidx libs和google-services插件添加到最新(4.1.0)后无法构建项目
- sql - 使用 Impala 在 id 字段上连接两个表
- javascript - 仅从 getElementsByClassName 获取所有元素的 Javascript 函数
- javascript - Electron:渲染器进程不渲染导航栏
- sqlite - Sqlite3 线程 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) 错误
- service-worker - 使用 sw-precache 在 dynamicUrlToDependencies 中没有显式声明的缓存 Url
- angular - Angular 项目部署在 Firebase 上但未显示网站
- android - Firestore 回收站视图
- r - 如何将字符串变量添加到带有按因子级别着色的标签的树状图中?