【发布时间】:2018-10-22 17:00:27
【问题描述】:
如何配置我的 razor 页面以接受多个路由?例如,如果我有一个剃须刀页面 ./Pages/Inovices/Overview.cshtml。我需要这个页面来处理 ~/invoices 和 ~/invoices/overview 的请求。目前我在 Index.cshtml 上使用 Handler 方法,但感觉应该有更简单的方法。有什么想法吗?
【问题讨论】:
如何配置我的 razor 页面以接受多个路由?例如,如果我有一个剃须刀页面 ./Pages/Inovices/Overview.cshtml。我需要这个页面来处理 ~/invoices 和 ~/invoices/overview 的请求。目前我在 Index.cshtml 上使用 Handler 方法,但感觉应该有更简单的方法。有什么想法吗?
【问题讨论】:
您可以使用AddPageRoute 为您的页面添加约定。这是您的示例的样子:
services.AddMvc(...)
.AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Invoices/Overview", "invoices");
});
这会为页面添加一条新路由,但也会保持现有路由不变。
【讨论】:
我有一个类似的场景,我需要支持 razor 页面的多个路由,还需要保留已重命名的 razor 页面的 URL,以便书签继续工作。为了解决这个问题,我选择使用重定向。方法如下:
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();
}
// ...
}
【讨论】: