我们正在为我们的应用程序使用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/
但是当我们省略一个尾部斜杠时,资源网址是
// Generates a resource url 'http://host.com:8081/content/scripts.js'
// which is bad
http://host.com:8081/module
有没有办法重定向到斜杠版本?或者至少检测是否存在尾部斜杠。
谢谢!
答案 0 :(得分:0)
这感觉有点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