首页 > 解决方案 > ASP.NET Core Razor 页面的路由

问题描述

我一直在寻找为 ASP.NET Core Razor Pages 配置默认路由的方法,但仍然没有成功。这是我的默认路由代码。还有什么我可以做的吗?顺便说一句,这是没有 MVC 的纯 Razor 页面。

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddDbContext<AppDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("AppDbContext")));

            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.RootDirectory = "/Bank";

            });
        }

标签: c#razorasp.net-core

解决方案


我对问题的理解(来自评论部分),您想要执行以下操作:

  1. 添加路由到自定义剃须刀页面。
  2. 更改登录页面重定向。

您可以执行以下操作以将自定义路由添加到剃须刀页面:

//This should be in the very end.
services.AddMvc().AddRazorPagesOptions(options =>
{
   //just to respect Microsoft way, it is better to have Pages folder
   //to contains your folders.
   options.RootDirectory = "/CustomFolder/Pages";
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

要更改登录页面,您需要执行以下操作:

  1. 将 [Authorize] 添加到您想要授权访问的页面。或遵循Microsoft 指南

如果您有 Microsoft 脚手架版的身份页面,例如:

services.AddDefaultIdentity<IdentityUser>()
   .AddEntityFrameworkStores<ApplicationDbContext>();

你需要用你自己的替换它Identity(除非有办法覆盖默认值)。因为默认设置会将登录路径设置为:/Identity/Account/Login.

在实现自己的身份之后,您可以设置 cookie 选项。

services.ConfigureApplicationCookie(options => {
   options.LoginPath = "/Bank/Login";
});

这些步骤对我有用。如果您坚持使用默认身份,您可以添加CookieAuthenticationEvents然后实现自己的OnRedirectToLogin.

编辑:这里有一些有用的网站:

  1. Razor 页面配置
  2. 配置 ASP.NET Core 标识
  3. 定制身份

推荐阅读