Error while using Middleware

Asked

Viewed 135 times

2

I’m trying to use Middleware, so that every time a user logs into the system it is being redirected to condominium registration screen, he can not use the system until you register at least 1 condominium.

But I’m getting the following errors:

inserir a descrição da imagem aqui

Code of my Middleware ~/Custom/Middleware/Redirectnocondominium.Cs

public class RedirectNoCondominium
{
    private readonly UserManager<ApplicationUsers> _userManager;
    private readonly ICondominiumService _condominiumManager;
    private readonly RequestDelegate _next;
    private readonly string path = "~/Condominium/Add";

    public RedirectNoCondominium(
        RequestDelegate next, 
        UserManager<ApplicationUsers> userManager,
        ICondominiumService condominiumManager)
    {
        _condominiumManager = condominiumManager;
        _userManager = userManager;
        _next = next;
    }

    public ClaimsPrincipal User { get; private set; }

    public async Task Invoke(HttpContext httpContext)
    {
        var user = await _userManager.GetUserAsync(User);

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

        if (result.Count() == 0 && httpContext.Request.Path != path)
        {
            httpContext.Response.Redirect(path);
        }
        else
            await _next(httpContext);
    }
}

And here at my startup.Cs I make his call.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMiddleware<RedirectNoCondominium>(); <-- aqui

        app.UseForwardedHeaders();

        app.Use(async (context, next) =>
        {
            if (context.Request.IsHttps || context.Request.Headers["X-Forwarded-Proto"] == Uri.UriSchemeHttps)
            {
                await next();
            }
            else
            {
                string queryString = context.Request.QueryString.HasValue ? context.Request.QueryString.Value : string.Empty;
                var https = "https://" + context.Request.Host + context.Request.Path + queryString;
                context.Response.Redirect(https);
            }
        });


        if (env.IsDevelopment())
        {

            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }


        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseNToastNotify();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
  • Matheus in my answer what were your problems found? Did you happen to use httpContext.RequestServices.GetService(typeof(UserManager<ApplicationUsers>)) that also solves. Please do not open several questions of the same doubt we will try to solve your problem by the initial doubt that is how it does, maybe we have to change something then communicate ...

1 answer

2


The solution is to inject in the method invoke

public class RedirectNoCondominium
{    
    private readonly ICondominiumService _condominiumManager;
    private readonly RequestDelegate _next;
    private readonly string path = "~/Condominium/Add";

    public RedirectNoCondominium(
        RequestDelegate next,         
        ICondominiumService condominiumManager)
    {
        _condominiumManager = condominiumManager;        
        _next = next;
    }

    public ClaimsPrincipal User { get; private set; }

    public async Task Invoke(HttpContext httpContext,
                             UserManager<ApplicationUsers> userManager)
    {
        var user = await userManager.GetUserAsync(User);

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

        if (result.Count() == 0 && httpContext.Request.Path != path)
        {
            httpContext.Response.Redirect(path);
        }
        else
            await _next(httpContext);
    }
}

Note is that the same code, but, will depend on how you did in the Startup.cs, example:

It has to be configured in the Startup.cs in the method ConfigureServices:

services.AddDefaultIdentity<IdentityUser>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();

in the Configure method after app.UseAuthentication();, example:

app.UseAuthentication();
app.UseMiddleware<RedirectNoCondominium>();

In the method of middlweare thus:

public class RedirectNoCondominium
{        
    private readonly RequestDelegate _next;
    private readonly string path = "/Condominium/Add";

    public RedirectNoCondominium(RequestDelegate next)
    {            
        _next = next;
    }


    public async Task Invoke(HttpContext httpContext, 
                             UserManager<IdentityUser> userManager)
    {
        if (httpContext.User.Identity.IsAuthenticated)
        {
            IdentityUser user = 
                await userManager.GetUserAsync(httpContext.User);
            var id = user.Id; // Id do usuário
            //trabalhe pra frente o seu código ...
            if (user != null)
            {
                if (httpContext.Request.Path.Value != path)
                {
                    httpContext.Response.Redirect(path);
                }
                else
                {
                    await _next(httpContext);
                }
            }
            else
            {
                await _next(httpContext);
            }
        }
        else
        {
            await _next(httpContext);
        }
    }
}
  • @Virgio Novic, with his answer I was able to solve the error, but when I keep the app.UseMiddleware<RedirectNoCondominium>(); in my file startup.cs he gives me the error Esta página não está funcionando localhost não consegue atender a esta solicitação no momento.- HTTP ERROR 500, but when I comment app.UseMiddleware<RedirectNoCondominium>(); in my file startup.cs works just right

  • You need to debug the expensive code! @Matheus to see where the error is on the server! , it may be your class, or else the injection is not working.

  • 1

    Another test you can do: httpContext.RequestServices.GetService(typeof(UserManager<ApplicationUsers>)); I have no way to test is with you this @Matheus

Browser other questions tagged

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