Search code examples
c#asp.net-core-mvcasp.net-identityasp.net-core-2.2

asp.net core mvc change default Identity area routes


asp.net core 2.2 Identity was added via

services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders()
        .AddDefaultUI();  

The login is set to "/Identity/Account/Login":

options.LoginPath = "/Identity/Account/Login";

Now how do I change the routes from the Identity area, which was added via the Startup.cs so that I can do for example:

https://www.example.com/admin instead of having https://www.example.com/identity/account/login

or

https://www.example.com/register so that it goes to HomeController->RegisterAction. This would allow me to catch and redirect the HomeController->RegisterAction it to HomeController->IndexAction in order to disable the registrations.


Solution

  • If anyone searches the answer for asp.net core mvc 2.2:

    When you call DefaultUI you don't have any specific pages or controllers to modify.

    You have to Scaffold the pages you want to modify.

    1. right mouse click the project
    2. Add --> New Scaffolded Item (if it is disabled, stop debugging/running)
    3. On the left select Identity and click Add
    4. Select your layout page (~/Views/Shared/_Layoutcshtml) to get correct layout
    5. select the page you want to override e.g. Account\Register
    6. Select your data context class (or create a new one by clicking [+])
    7. Click Add

    Now you will see in /Areas/Identity/Pages/Account/Register.cshtml

    Expand Register.cshtml and open the file Register.cshtml.cs. ('codebehind')

    Now if you want to disable registrations, you can replace

    public void OnGet(string returnUrl = null)
    {
      ReturnUrl = returnUrl;
    }
    

    with:

    public IActionResult OnGet(string returnUrl = null) => RedirectToPage("/Account/Login"); // disable registrations
    

    Additional info:

    In case any [MSFT] is reading this: it would be great if you could disable registrations or change redirect routes via Startup.cs without having to scaffold (which would allow you to update packages without having the UI you once scaffolded at version x.