使用多个路由的.NET Core Razor页面

3
我该如何配置我的 Razor 页面,使其接受多个路由?例如,如果我有一个 Razor 页面 ./Pages/Inovices/Overview.cshtml,我需要让该页面处理~/invoices~/invoices/overview的请求。目前我正在使用 Index.cshtml 上的处理程序方法,但感觉应该有更简单的方法。你有什么想法吗?
2个回答

3

您可以使用AddPageRoute为您的页面添加一个约定。下面是示例:

services.AddMvc(...)
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/Invoices/Overview", "invoices");
    });

这将为页面添加一个新的路由,同时保留现有的路由不变。

0
我曾遇到过一个类似的情况,需要为 Razor 页面支持多个路由,并保留已重命名 Razor 页面的 URL,以便书签继续有效。为了解决这个问题,我选择使用重定向。以下是解决方法:
  • 在我的 Startup.cs 文件中,我添加了一个 HandleRedirects 方法,定义了重定向中间件以及要重定向的路由:
private void HandleRedirects(IApplicationBuilder app)
{
    // Old Url, New Url
    var redirects = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        {"/Reports/BatchReport", "/Reports/BatchDetailReport" }
    };

    app.Use(async (context, next) =>
    {
        if (redirects.TryGetValue(context.Request.Path, out var redirectUrl))
        {
            context.Response.Redirect(redirectUrl);
            return;
        }

        await next();
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    HandleRedirects(app);

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    // ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接