I have a class for Validation which is:
public class PageValidation:ValidationAttribute
{
private readonly string UserKey;
private readonly HttpContext _context;
public PageValidation(IHttpContextAccessor contextAccessor,string UserKey)
{
this.UserKey = UserKey;
_context = contextAccessor.HttpContext;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var ActiveUserString = _context.Session.GetString("ActiveUserSession");
var ActiveUser = JsonSerializer.Deserialize<UserModel>(ActiveUserString);
if (ActiveUser.AuthCheck(UserKey)) return ValidationResult.Success;
else throw new ApplicationException("Erişim yetkiniz yok!");
}
}
And I want to call this from my controller which is:
[PageValidation(null, "Company")]
public IActionResult CompanyAndDepartments(string ViewType)
The problem is I cant send first parameter of PageValidation’s cunstructor correctly. As you see it is null and it gives me error.
You can’t inject objects into attributes like this. However the ValidationContext
parameter passed into the IsValid
method has all you need. For example:
public class PageValidation : ValidationAttribute
{
private readonly string _userKey;
public PageValidation(string UserKey)
{
_userKey = UserKey;
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var httpContextAccessor = validationContext
.GetService<IHttpContextAccessor>();
var httpContext = httpContextAccessor.HttpContext;
var ActiveUserString = httpContext.Session.GetString("ActiveUserSession");
var ActiveUser = JsonSerializer.Deserialize<UserModel>(ActiveUserString);
if (ActiveUser.AuthCheck(UserKey)) return ValidationResult.Success;
else throw new ApplicationException("Erişim yetkiniz yok!");
}
}