简体   繁体   中英

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. 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.

Alternative solutions: 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.

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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