Napal
Napal

Reputation: 284

How to add custom routes in ASP.NET Core MVC for Identity?

I'm used to work with ASP.NET MVC framework but now I've moved on to ASP.NET Core MVC, and routes seem to be something else.

This is the project structure (Identity is scaffolded)

enter image description here

This is how I can add a custom route like in classic ASP.NET MVC:

routes.MapRoute(
       name: "About",
       url: "About",
       defaults: new { controller = "Home", action = "About" }
    );

In this example I'm using https://localhost/About instead of https://localhost/Home/About

I'm trying to achieve the same thing using ASP.NET Core MVC, but I can't find any article related to this and the "url" attribute does not exist anymore.

app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Charts}/{action=Index}/{id?}");
            endpoints.MapControllerRoute(
                name: "Register",
                pattern: "{controller=Identity/Account}/{action=Register}");                
            endpoints.MapRazorPages();
        });

I would like to add a custom route to https://localhost/Identity/Account/Register to https://localhost/Register

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using ERP_MKM.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ERP_MKM.Models;
using Microsoft.AspNetCore.Identity.UI.Services;
using ERP_MKM.Services;

namespace ERP_MKM
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySql(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddIdentityCore<ApplicationUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultUI();
            services.AddTransient<IEmailSender, EmailSender>(i =>
                new EmailSender(
                    Configuration["EmailSender:Host"],
                    Configuration.GetValue<int>("EmailSender:Port"),
                    Configuration.GetValue<bool>("EmailSender:EnableSSL"),
                    Configuration["EmailSender:UserName"],
                    Configuration["EmialSender:Password"]
                )
            );  
            services.AddControllers().AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );
            services.AddControllersWithViews();
            services.AddRazorPages().AddRazorRuntimeCompilation();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Charts}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                     name: "Register", 
                     pattern: "Register", 
                     defaults: new { area = "Identity", controller = "Account", action = "Register" });             
                endpoints.MapRazorPages();
            });
        }
    }
}

Upvotes: 1

Views: 3725

Answers (1)

Yehor Androsov
Yehor Androsov

Reputation: 6152

Controllers mapping

endpoints.MapControllerRoute(
    name: "any-route-name",
    pattern: "register",
    defaults: new { area = "Identity", controller = "Account", action = "Register" }
);

For Razor pages there are AddPageRoute and AddAreaPageRoute methods. This code should be inside ConfigureServices method

services.AddRazorPages(options =>
{
    options.Conventions.AddAreaPageRoute("Identity", "/Account/Register", "/Register");
    options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "/Login");
});

And don't forget to have line of code to enable pages in endpoints

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapRazorPages(); // this one
});

You can scaffold page to include and modify it in your project using Visual Studio. enter image description here enter image description here

Select required pages, select user context and click OK. This screenshot is also useful to find out all paths to pages in Identity area.

enter image description here

Upvotes: 4

Related Questions