首页 > 解决方案 > 将模型值设置为小写的 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

标签: c#asp.net.net.net-core

解决方案


替代解决方案: 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();
}

推荐阅读