我们正在为我们的应用程序使用 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/