更改模型验证属性asp.net core 3.1的默认ErrorMessage

时间:2020-07-21 11:22:13

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

如何避免每次都写[Required(ErrorMessage="My custom error message")]并为整个项目设置默认的ErrorMessage

3 个答案:

答案 0 :(得分:0)

这就是我的方法。

在Startup.cs-> Configure()中,设置您的异常处理程序中间件:

app.UseExceptionHandler("/Home/Error");

这会将所有异常重定向到本地控制器错误方法。 现在,为“首页/错误”设置视图模型。

在ErrorViewModel.cs中:

public class ErrorViewModel
{
    public string RequestId { get; set; }   
    public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);    
    public string ExceptionMessage { get; set; }
    public bool ShowExceptionMessage => !string.IsNullOrEmpty(ExceptionMessage);
}

在HomeController中:

[AllowAnonymous]
public IActionResult Error()
{
    ErrorViewModel errorViewModel = new ErrorViewModel();
    errorViewModel.RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;

    string message = "your message";
    errorViewModel.ExceptionMessage = message;
    _logger.LogError(message);
    return View(errorViewModel);
}

此时,您的自定义错误消息将可以在“错误”视图页面的模型中访问。

答案 1 :(得分:0)

如何避免编写[Required(ErrorMessage =“我的自定义错误 message“)]并为整个设置默认的ErrorMessage 项目?

您可以创建custom attributes来自动生成错误消息,但是不可避免地需要向相应的字段添加属性以表示您对字段的约束。


更新

如果您有多个不同的验证要求,则可以合并到自定义属性中,并继承ValidationAttribute类。

前提是您需要传递参数以区分它们

有一种情况:

public class CustomRequired : ValidationAttribute
    {
        public CustomRequired(string sepcialType)
        {
            this.SepcialType = sepcialType;
        }
        public string SepcialType { get; private set; }  

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string errorType;
            if (value == null)
            {
                errorType = "required"; 
            }
            else if (!string.IsNullOrEmpty(SepcialType) && !IsValidEmail(value.ToString()))
            {
                errorType = "not valid";
            }
            else
            {
                return ValidationResult.Success;
            }
            ErrorMessage = $"{validationContext.DisplayName}  field is {errorType}.";
            return new ValidationResult(ErrorMessage);
        }
        bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
    }
  

班级:

 public class ThemTest
    {
        public int Id { get; set; }
        [CustomRequired("")]
        public string Name { get; set; }
        [CustomRequired("")]
        public string Theme { get; set; }
        [CustomRequired("Email")]
        public string Email { get; set; }
    }

验证视图:

@model ThemTest
@{
    ViewData["Title"] = "TestAttr";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>TestAttr</h1>
<form method="post">
    <div class="form-row">
        <label asp-for="Name"></label>
        <input asp-for="Name" type="text" class="form-control" />
        <span asp-validation-for="Name" class="field-validation-valid text-danger"></span>
    </div>
    <div class="form-row">
        <label asp-for="Theme"></label>
        <input asp-for="Theme" type="text" class="form-control" />
        <span asp-validation-for="Theme" class="field-validation-valid text-danger"></span>
    </div>
    <div class="form-row">
        <label asp-for="Email"></label>
        <input asp-for="Email" type="text" class="form-control" />
        <span asp-validation-for="Email" class="field-validation-valid text-danger"></span>
    </div>
    <input id="Submit1" type="submit" value="submit" class="btn btn-primary" />
</form>

这是测试结果:

enter image description here

答案 2 :(得分:0)

经过研究,我发现了使用某种本地化和资源文件的唯一方法。您仍然需要编写[Required(ErrorMessage="<Resource Key Goes Here>")]。但是,仅使用诸如[Required(ErrorMessage=Class.Property)]这样的常量消息的好处是您可以访问资源文件中的属性变量。

这是我的方法:

  1. 在名为 Resources
  2. 的根目录中创建一个文件夹
  3. 资源文件夹中创建一个名为 ValidationMessages.cs
  4. 的空类
  5. 资源文件夹中创建一个名为 ValidationMessages.resx
  6. 的空文件
  7. 使用VisualStudio编辑器编辑 .resx 文件
  8. 示例键,[StringLength]属性的值对:“ StringLength”,“最小长度{2},最大长度{1}”
  9. 在模型中使用属性[StringLength(20, MinimumLength = 10, ErrorMessage = "StringLength")]
  10. 将此代码添加到 Startup.cs
    using MyProject.Resources;
    ...
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddDataAnnotationsLocalization(options => {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                        factory.Create(typeof(ValidationMessages));
                });
        ...

完成了。