url - 南希导航到没有斜杠的 URL?

标签 url path nancy

我们正在为我们的应用程序使用 Nancy 框架,该框架在控制台应用程序中自托管。
加载没有尾部斜杠的 URL 时会出现问题。

假设我们将页面托管在

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

然后它为我们提供一个 html 页面,其中包含具有如下相对路径的资源:
content/scripts.js

当您输入网址时,一切正常,例如
// 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

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

谢谢!

最佳答案

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

Get["/module/"] = o =>
{
    if (!Context.Request.Url.Path.EndsWith("/"))
        return Response.AsRedirect("/module/" + Context.Request.Url.Query, RedirectResponse.RedirectType.Permanent);
    return View["module"];
};
Request可从 Context 访问让您查看路径是否有斜杠并重定向到“斜杠”版本。
我将其包装为扩展方法(适用于我非常简单的用例):
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

关于url - 南希导航到没有斜杠的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861200/

相关文章:

python - 在站点 url.py 中指定 Django URL-Namespaces 的原因是什么?

asp.net-mvc-3 - 我可以隐藏 URL 中的请求信息吗?

css - 如何在 google chrome 的开发者工具中显示样式表的路径?

python:将目录向上两级

Nancy:基本模块未触发

rest - 在 Unity3d 中运行 REST 服务器

java - 为什么 "+"添加到我在 url 生成器中的所有坐标?

java - 如果我想发送http请求,用Java的outputstream写什么呢?

Node.js - 如何跨平台找到 'desktop'目录路径?

razor - (Nancy) Razor View Engine 部分 View 渲染完整 HTML