【问题标题】:Logging from validator class从验证器类记录
【发布时间】:2017-04-29 02:28:05
【问题描述】:

我有一个简单的类,如下在 web API 中使用。如您所见,它有一个通过属性应用的验证器

[CustomerNameValidator]
public class Customer
{
    public string CustomerName { get; set; }
}

Validator 类如下所示

public class CustomerNameValidatorAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        Customer customer = (Customer)validationContext.ObjectInstance;

        if ( string.IsNullOrEmpty(customer.CustomerName))
        {
            return new ValidationResult("Invalid customer Name");
        }


        return ValidationResult.Success;
    }
}

我想在 IsValid 方法中添加一些日志记录。我正在使用 Startup 类设置的其他地方进行日志记录,如下所示。

public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();


    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    loggerFactory.AddNLog();
}

如何在验证属性类中使用记录器?

【问题讨论】:

    标签: c# validation asp.net-web-api asp.net-core .net-core


    【解决方案1】:

    ValidationContextpopulatedHttpContextIServiceProvider 实例)的 RequestServices 属性。这意味着您可以使用ValidationContext 上的GetService method 解析服务。

    例如:

    var logger = (ILogger<CustomerNameValidatorAttribute>)validationContext.GetService(typeof(ILogger<CustomerNameValidatorAttribute>));
    

    【讨论】:

    • 如果添加using Microsoft.Extensions.DependencyInjection;,则可以使用var logger = validationContext.GetService&lt;ILogger&lt;CustomerNameValidatorAttribute&gt;&gt;();而不进行强制转换
    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    相关资源
    最近更新 更多