我想为用户提供一个简短的 URL www.example.com/books/DOP/并将他们重定向到 www.example.com/Books/Daughters-of-the-Pioneers-Autobiographies/index.html。目的是使用户不必键入完整的 url。
我尝试使用 OnGet 上的重定向创建 Razor 页面,但没有成功。有什么想法吗?
namespace SLCore21.Pages.Books.DOP
{
public class indexModel : PageModel
{
public void OnGet()
{
LocalRedirectPermanent("~/Books/Daughters-of-the-Pioneers-Autobiographies/index.html");
}
}
}
最佳答案
对于您正在使用的方法,您需要返回 LocalRedirectPermanent
的结果,这还需要更改 OnGet
处理程序的签名以返回例如一个 IActionResult
。这是一个更新的示例:
public IActionResult OnGet()
{
return LocalRedirectPermanent("~/Books/Daughters-of-the-Pioneers-Autobiographies/index.html");
}
为此使用专用的 Razor 页面可能有点过分:我将引入一个自定义中间件,它使用源到目标的映射并在那里执行此类重定向。下面是一个示例中间件函数,用于演示其工作原理:
var redirectMap = new Dictionary<string, string>
{
["/books/dop"] = "/Books/Daughters-of-the-Pioneers-Autobiographies/index.html"
};
app.Use(async (ctx, next) =>
{
if (redirectMap.TryGetValue(
ctx.Request.Path.ToString().TrimEnd('/').ToLower(),
out var redirectPath))
{
ctx.Response.Redirect(redirectPath, true);
return;
}
await next();
});
我在这里添加了一个硬编码的 redirectMap
,但如果这是经常更改的东西,我会把它移到配置中。
代码本身很简单 - 它查看传入的请求,从路径中删除尾随的 /
,将其转换为小写,然后检查该值是否存在于 redirectMap
。如果确实存在,代码将执行重定向(true
表示永久)并使管道短路。否则,执行将传递给下一个中间件。
关于c# - 如何将短网址重定向到更具描述性的长网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174669/