【问题标题】:How to add custom routes in ASP.NET Core MVC for Identity?如何在 ASP.NET Core MVC 中为 Identity 添加自定义路由?
【发布时间】:2021-02-23 16:47:45
【问题描述】:

我习惯使用 ASP.NET MVC 框架,但现在我转向 ASP.NET Core MVC,路由似乎是别的东西。

这是项目结构(身份是脚手架)

这就是我可以像在经典 ASP.NET MVC 中一样添加自定义路由的方法:

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

在此示例中,我使用 https://localhost/About 而不是 https://localhost/Home/About

我正在尝试使用 ASP.NET Core MVC 实现相同的目标,但我找不到任何与此相关的文章,并且“url”属性不再存在。

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

我想将自定义路由添加到https://localhost/Identity/Account/Registerhttps://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();
            });
        }
    }
}

【问题讨论】:

  • 你可以试试:endpoints.MapControllerRoute(name: "Register", pattern: "Register", defaults: new { area = "Identity", controller = "Account", action = "Register" } );
  • 它不起作用,一直显示空白视图
  • 作为替代方案,您可以使用 app.UseEndpoints(endpoints => { endpoints.MapControllers(); });在 Startup.cs 和 AccountController 内的方法“Register”上使用路由属性 [Route("Register")]。但在其他控制器上,您必须设置路由属性,例如 [Route("[controller]")]。

标签: c# asp.net-core routes asp.net-core-mvc asp.net-identity


【解决方案1】:

控制器映射

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

对于 Razor 页面,有 AddPageRouteAddAreaPageRoute 方法。这段代码应该在ConfigureServices 方法中

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

别忘了有一行代码来启用端点中的页面

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

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

您可以使用 Visual Studio 在您的项目中包含和修改页脚架。

选择所需页面,选择用户上下文并单击确定。此屏幕截图对于找出身份区域中页面的所有路径也很有用。

【讨论】:

  • 使用附加到主帖的 startup.cs 文件对其进行了更新
  • startup.cs 无济于事。显示项目的目录结构
  • 将结构添加为图像,值得一提的是,身份是脚手架,并且它不存在于 Controllers 文件夹中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
相关资源
最近更新 更多