c# - 如何将短网址重定向到更具描述性的长网址

标签 c# asp.net-core

我想为用户提供一个简短的 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/

相关文章:

c# - System.Diagnostics.Trace、System.Diagnostics.Debug 和 System.Console 之间有什么区别?

c# - 使用 API 在亚马逊上更新商品数量时出错

c# - 修改中间件中的响应头时出错

c# - 对 asp.net mvc 应用程序有用的库

c# - 如何在类的列表类型上使用 foreach 循环?

c# - .NET 服务器如何将文件处理结果推送到客户端 jQuery?

c# - 无法在 Visual Studio Build Framework 中选择 .NET Core 2.2

.net - 托管在 Windows 服务中的 Kestrel 的 Windows 身份验证

c# - JWT 访问 token 与刷新 token (创建)

azure - 抛出异常 : 'System.InvalidOperationException' in Microsoft. Extensions.DependencyInjection