Search code examples
c#asp.net-coreconstructorrazor-pages

ASP.NET CORE Redirect inside the constructor


I am developing a web project using asp.net core 7 and razor pages. I'm dealing with a routing issue. In the Controller, I check whether the user is logged into each method. I think this does not comply with the DRY principle and I try to write clean code as much as I can. I thought about moving this control to the constructor, but I cannot use redirect in the constructor. Is there any way to do this?


Solution

  • I found a different solution to this problem.

    Here I added this to the Configure method of the Startup.cs file

    app.UseSession();
    
    app.Use(async (context, next) =>
    {
        string CurrentUserIDSession = context.Session.GetString("userToken");
        if (!context.Request.Path.Value.Contains("/User/Login"))
        {
            if (string.IsNullOrEmpty(CurrentUserIDSession))
            {
                var path = $"/User/Login?ReturnUrl={context.Request.Path}";
                context.Response.Redirect(path);
                return;
            }
    
        }
        await next();
    });