简体   繁体   English

将模型值设置为小写的 ASP.NET Core 2.1 属性

[英]ASP.NET Core 2.1 Attribute to set model value to lowercase

I would like to know if there's a way to force the value of some properties to always be lowercase or uppercase when I receive the model at my controller.我想知道当我在控制器上接收到模型时,是否有办法强制某些属性的值始终为小写或大写。 Preferably in a clean way, like using attributes.最好以一种干净的方式,比如使用属性。

Example:例子:

Controller:控制器:

[HttpPost]
public async Task<Model> Post(Model model)
{
    //Here properties with the attribute [LowerCase] (Prop2 in this case) should be lowercase.
}

Model:模型:

public class Model
{
    public string Prop1 { get; set; }

    [LowerCase]
    public string Prop2 { get; set; }
}

I've heard that changing values with a custom ValidationAttribute is not a good thing.我听说使用自定义ValidationAttribute更改值不是一件好事。 Also decided to create a custom DataBinder , but didn't find exactly how I should implement it, when tried to, just received null in my controller.还决定创建一个自定义DataBinder ,但没有找到我应该如何实现它的确切方法,当尝试时,我的控制器中只收到null

Alternative solutions: Fluent API:替代解决方案:Fluent API:

modelBuilder.Entity<Model>()
    .Property(x => x.Prop2)
    .HasConversion(
        p => p == null ? null : p.ToLower(),
        dbValue => dbValue);

Or, encapsulate within the class itself, using property with backing field:或者,使用带有支持字段的属性封装在类本身中:

private string _prop2;
public string Prop2
{ 
    get => _prop2;
    set => value?.ToLower();
}

Decided to use a custom JsonConverter.决定使用自定义 JsonConverter。

public class LowerCase : JsonConverter
{
    public override bool CanRead => true;
    public override bool CanWrite => false;
    public override bool CanConvert(Type objectType) => objectType == typeof(string);

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value.ToString().ToLower();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

public class Model
{
    public string Prop1 { get; set; }

    [JsonConverter(typeof(LowerCase))]
    public string Prop2 { get; set; }
}

Still think there's a better way tho, will keep looking for something.仍然认为有更好的方法,将继续寻找一些东西。

You can make readonly property您可以制作只读属性

 public string Prop2 { get{return Prop1.ToLower()}}

or like that或那样

 public string Prop2 => Prop1.ToLower();

You can build a class constructor like this:您可以像这样构建类构造函数:

public class Model
{
        public Model()
        {
            this.Prop2 = this.Prop2.ToLower();
        }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM