How can I redirect to the login view in case the user is not logged in?

Viewed 55

I am doing the validations of my Logueo view, and I want that if the user is not logged in, he cannot access the Index, I want to force him to register yes or yes.

From what I was seeing, it can be done with the ActionFilterAttribute class, and then validating that a Session variable is not null, in case it is, it automatically redirects you to Login.

My problem is that I am developing my application in ASP.NET Core, and from what I understood, Session cannot be used in Core, and you have to use other alternatives like TempData[] or Cookies .

Could someone explain me better why Session cannot be used and if they can help me with redirecting the user to the Login view in case he is not logged in?

public class ValidateSession: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    { 
        if(HttpContext.Session.GetString("User") == null)
        {
            context.Result = new RedirectResult("~/Home/Login");
        }
        base.OnActionExecuting(context);    
    }
}

An Object reference is required for the non-static field, method, or property 'HttpContext.Session'

1 Answers

You don't need Session. You simply need to add the below snippet to your Program.cs file:

builder.Services.AddMvc(options =>
{
    options.Filters.Add(new AuthorizeFilter());
});

This is assuming that you're using Identity to manage your users and the MVC middleware. Also make sure that you're using the MVC.Authorization package within your Program.cs file.

using Microsoft.AspNetCore.Mvc.Authorization;
Related