【问题标题】:Nancy navigation to URL without trailing slash?南希导航到没有斜杠的 URL?
【发布时间】:2015-01-07 18:48:48
【问题描述】:

我们正在为我们的应用程序使用 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 application 管道并添加尾部斜杠或执行 theredirectct
  • 挂钩到之前不起作用,因为在访问带有或不带有斜杠的 URL 时,我得到了相同的 URL。我无法检测到何时缺少斜杠以及何时进行重定向。
  • 如果我创建了两个路由,Get["/module"]Get["/module/"],那么对 /module/module/ 的请求都会由Get["/module/"] route - 所以似乎没有办法区分它们?

标签: url path nancy


【解决方案1】:

这感觉有点hacky,但它有效:

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");

This is worth reading though before going with a solution such as this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 2016-11-29
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    相关资源
    最近更新 更多