南希如何在没有尾部斜杠的情况下导航到URL?

4

我们正在使用Nancy框架开发自托管控制台应用程序。

当没有斜杠的URL被加载时,问题就出现了。

假设我们将页面托管在

http://host.com:8081/module/

然后它会向我们提供一个包含相对路径资源的HTML页面,如下所示:
content/scripts.js

当您输入类似以下的URL时,一切都正常运作:

// Generates a resource url 'http://host.com:8081/module/content/scripts.js' 
// which is good
http://host.com:8081/module/ 

但是当我们省略尾部斜杠时,资源的URL就会变成:

// Generates a resource url 'http://host.com:8081/content/scripts.js' 
// which is bad
http://host.com:8081/module

有没有办法重定向到带斜杠版本?或者至少检测是否存在斜杠。感谢!

你可能可以钩入应用程序管道的“Before”事件,并添加尾部斜杠或执行重定向。 - Christian Horsdal
Hooking到Before不起作用,因为访问带或不带尾随斜杠的URL时,我得到相同的URL。我无法检测缺少尾随斜杠的情况以及何时进行重定向。 - Drasius
如果我创建两个路由,Get ["/module"]Get ["/module/"],那么对于 /module/module/ 的请求都将由 Get ["/module/"] 路由处理 - 所以似乎没有办法区分它们? - rogersillito
1个回答

0
这种方法有点取巧,但它能够正常工作:
Get["/module/"] = o =>
{
    if (!Context.Request.Url.Path.EndsWith("/"))
        return Response.AsRedirect("/module/" + Context.Request.Url.Query, RedirectResponse.RedirectType.Permanent);
    return View["module"];
};

Context 中可访问的 Request 可让您查看路径是否具有尾随斜杠并重定向到“斜杠”版本。我将其封装为扩展方法(适用于我的非常简单的用例):

public static class NancyModuleExtensions
{
    public static void NewGetRouteForceTrailingSlash(this NancyModule module, string routeName)
    {
        var routeUrl = string.Concat("/", routeName, "/");
        module.Get[routeUrl] = o =>
        {
            if (!module.Context.Request.Url.Path.EndsWith("/"))
                return module.Response.AsRedirect(routeUrl + module.Request.Url.Query, RedirectResponse.RedirectType.Permanent);
            return module.View[routeName];
        };
    }
}

在模块中使用:

// returns view "module" to client at "/module/" location
// for either "/module/" or "/module" requests
this.NewGetRouteForceTrailingSlash("module");

在采用此类解决方案之前,阅读这篇文章是值得的


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