Custom Data Annotations for validation

Asked

Viewed 180 times

4

I want to create a Data Annotation to be able to check in ALL pages of my application if the user who is logging in already has 1 Condomínio registered, if there is no registered condominium it redirects to the condominium registration screen.

What I have at the moment is this:

protected async Task<ValidationResult> IsValidAsync(ValidationContext validationContext)
{
    var userId = await _userManager.GetUserAsync(user);

    List<ApplicationCondominium> result = await _condominiumManager.GetCondominiumAsync(userId.Id);

    if (result.Count() == 0)
    {
        return ValidationResult.
    }
    else
    {
        return ValidationResult.Success;
    }
 }

They could help me because I need this validation on all pages of my application.

1 answer

4


Basically you need to create a Middleware, that when checking your code whether or not a condominium exists makes the redirect. Example:

Create a class:

public class RedirectNoApartment
{
    private readonly RequestDelegate _next;
    private readonly bool status = true;
    private readonly string path = "/home/about";

    public RedirectNoApartment(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext httpContext)
    {
        status = ; // aqui você adiciona o código de verificação retornando true ou false
        if (!status && httpContext.Request.Path != path)
        {
            httpContext.Response.Redirect(path);                
        } 
        else
            await _next(httpContext);
    }
}

Within this class there is a bool status which is a variable for you to search in your bank and bring whether or not there is a condominium for a particular user and also a string path that your default redirect to load the condominium registration page.

Now get in the file startup.cs below the configuration connection to the database add this line

app.UseMiddleware<RedirectNoApartment>();

ready every time it will check whether or not the user has registered condominium

This code can be better prepared and suited to your needs, this is an example be to see your reality.

  • I tried to do this but apparently it is not working for me as I am getting the following error InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager1[Konbase.Models.Applicationusers]' from root Provider.`

  • You can’t solve an injection so it can be so much, what is your code! @Matheus

  • I asked this question to solve this problem, https://answall.com/questions/372861/erro-ao-usar-middleware, I put all the code there

  • @Matheus I think he will not be able to solve so, even if you have authenticated user he already gives you this information in Request, look at the code: var id = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; and another thing this answer is the primary solution of your problem

  • I tested this solution you gave me, but it does not find Httpcontext

  • @Matheus is httpContext.User is the same as in invoke! method, but in the other answer you have already been told how to do

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.