Home > Back-end >  How to properly route unauthenticated user to the Login Page in MVC .NET6
How to properly route unauthenticated user to the Login Page in MVC .NET6

Time:11-19

The only users that should see the list of contacts are authenticated users.

Inside the Contacts Controllers, I've been testing different file paths to route the unauthenticated users to the login screen to no avail.

When routing to anything inside the Area folder, exactly how would you go about writing the file path?

I've tried:

Areas/Identity/Pages/Account/Manage/Login.cshtml

~/Areas/Identity/Pages/Account/Manage/Login.cshtml

~/Account/Login

namespace ContactPro.Controllers
{
    public class ContactsController : Controller
    {
        private readonly ApplicationDbContext _context;

        public ContactsController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index()
        {
          if (User.Identity != null &&  User.Identity.IsAuthenticated)
          {
            return View(await _context.Contacts.ToListAsync());
          }

          else
          {
            return View("~/Account/Login");
          }

        }
         
     }
}

CodePudding user response:

But you can't redirect to a view that doesn't belong to the redirecting controller and isn't shared. Method View accepts a file name without path. It looks for the specified view in folder /YourProjectName/Views/RedirectingControllerName and in folder /YourProjectName/Views/Shared.

I advise you to use redirecting to action, not to a view. Create an action that will just return the view you need (in the controller that owns the needed view) and redirect to it when you need:

return RedirectToAction("ActionName", "ControllerName");

CodePudding user response:

The right way to do it would be to use the [Authorize] attribute on your controller or actionmethod that requires logged in users. You can then define to what actionresult they should be redirected if they are not authenticated, in your program startup, when configuring your authentication.

  • Related