Search code examples
c#asp.net-mvc-routing.net-6.0

How to properly route unauthenticated user to the Login Page in MVC .NET6


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");
          }

        }
         
     }
}

Solution

  • 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");