C# 从验证程序类进行日志记录
我在WebAPI中使用了一个简单的类,如下所示。正如您所看到的,它有一个通过属性应用的验证器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
[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
属性。这意味着您可以使用onValidationContext
从it解析服务
例如:
var logger = (ILogger<CustomerNameValidatorAttribute>)validationContext.GetService(typeof(ILogger<CustomerNameValidatorAttribute>));
var logger=(ILogger)validationContext.GetService(typeof(ILogger));
如果使用Microsoft.Extensions.DependencyInjection添加代码>,您可以使用var logger=validationContext.GetService()代码>无强制转换