Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net core get user in ValidationAttribute

I am trying to access the current user (i.e. ClaimsPrincipal from identity) in a custom ValidationAttribute, and I haven't figured out how I could do that.

public class UniqueTitleValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      // var user = ?
    }
}

I know that I could access the user from a HttpContext (but I don't know how to get to the latter).

The main problem is that I don't have access to the User. When I use a custom ValidatorAttribute on a property, when the property gets constructed the User (or also HttpContext) is null. Meaning that I can't e.g. give the User to the Validator's constructor. That's why I'm wondering how the Validator could be made to know something about the User (and/or its claims). If I can access any of e.g. HttpContext or User inside the validator, I can get to all the other runtime information as well. Is my question understandable?

like image 789
Doidel Avatar asked Oct 28 '18 11:10

Doidel


People also ask

What is ModelState in asp net core?

When we talk about ModelState , we mean ModelState property of the ControllerBase abstract class in the Microsoft. AspNetCore. Mvc namespace. It is of ModelStateDictionary type and it represents errors that come from two subsystems: model binding and model validation.

What is ValidationAttribute?

ValidationAttribute class is included in the DataAnnotations namespace. It helps you to validate the model data received from the user. It gives you many inbuilt validation attributes like StringLength, Required, DataType for validating the model.

How can use client side validation in asp net core?

The ASP.NET core includes unobtrusive client-side validation libraries, which makes it easier to add client side validation code, without writing a single line of code. In the previous tutorial on server side validation, we looked at how data annotations attributes are used by the Model Validator to validate the Model.


1 Answers

ValidationContext has its own GetService method, which is preconfigured to use the ASP.NET Core Dependency Injection container, IServiceProvider, when resolving services. Here's an example:

public class UniqueTitleValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));
        var user = httpContextAccessor.HttpContext.User;

        ...
    }
}

To get to HttpContext, use IHttpContextAccessor, which is resolved here using GetService as described above. You'll need to make sure you've registered this with DI, using e.g. AddHttpContextAccessor.

like image 87
Kirk Larkin Avatar answered Sep 23 '22 03:09

Kirk Larkin