Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从验证程序类进行日志记录_C#_Validation_Asp.net Web Api_Asp.net Core_.net Core - Fatal编程技术网

C# 从验证程序类进行日志记录

C# 从验证程序类进行日志记录,c#,validation,asp.net-web-api,asp.net-core,.net-core,C#,Validation,Asp.net Web Api,Asp.net Core,.net Core,我在WebAPI中使用了一个简单的类,如下所示。正如您所看到的,它有一个通过属性应用的验证器 [CustomerNameValidator] public class Customer { public string CustomerName { get; set; } } 验证程序类如下所示 public class CustomerNameValidatorAttribute : ValidationAttribute { protected override Valid

我在WebAPI中使用了一个简单的类,如下所示。正如您所看到的,它有一个通过属性应用的验证器

[CustomerNameValidator]
public class Customer
{
    public string CustomerName { get; set; }
}
验证程序类如下所示

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

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

验证上下文具有
HttpContext
实例的
RequestServices
属性。这意味着您可以使用on
ValidationContext
从it解析服务

例如:

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

如果使用Microsoft.Extensions.DependencyInjection添加
,您可以使用
var logger=validationContext.GetService()无强制转换