我在我的 .net 网站中使用路由。
我想要这个网址
http://www.website.com/condos/rent/{state}/{area}
前往 http://www.website.com/condos.aspx
然后选择州和地区。
这很好用:
routes.MapPageRoute("CondosForRentInArea", "condos/rent/{state}/
{area}", "~/condos.aspx");
但是我在使用 Javascript 时遇到了一些问题。因为我不会写:
routes.MapPageRoute("StateAreaJS", "condos/rent/{state}/{area}/scripts/
{filename}.js", "~/scripts/{filename}.js");
我在 Stackoverflow 上发现了另一个问题:Wildcards with ASP.NET MVC MapPageRoute to support organizing legacy code
但是我没有在这个网站上使用 MVC。我试过这个:
routes.Add("CondosRentStateAreaJS", new Route("condos/rent/{state}/{area}/scripts/
{filename}.js", new StateAreaJSRouteHandler()));
和:
public class StateAreaJSRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string filename = requestContext.RouteData.Values["filename"] as string;
if (string.IsNullOrEmpty(filename))
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.StatusCode = 404;
requestContext.HttpContext.Response.End();
}
else
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.ContentType = "text/javascript";
// find physical path to image here.
string filepath = requestContext.HttpContext.Server.MapPath("~/scripts/" + filename + ".js");
requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();
}
return null;
}
}
不过我不认为代码会被调用,因为在“string filename...”行中放置一个断点永远不会命中。
奇怪的是,CSS 在那里,服务器在文件夹/文件名之前插入 ../../../但缺少 JS。
那么我如何正确地将/state/area/scripts/file.js 设为 "~/scripts/file.js"
?
---------------- 编辑----------------
你绝对让我走上了正确的轨道。我应该通过代码隐藏添加脚本和样式表。我最终得到了这样一个很好的解决方案:
HtmlGenericControl validatejs = new HtmlGenericControl("script");
validatejs.Attributes.Add("type", "text/javascript");
validatejs.Attributes.Add("src", ResolveUrl("~/scripts/validate.js"));
this.Page.Header.Controls.Add(validatejs);
HtmlLink fontscss = new HtmlLink();
fontscss.Href = "~/styles/fonts.css";
fontscss.Attributes.Add("rel", "stylesheet");
fontscss.Attributes.Add("type", "text/css");
this.Page.Header.Controls.Add(fontscss);
而且我只想补充(对于其他 google 员工)这种方法使我能够删除我的 JS 和 CSS CustomRouteHandlers,使整个项目更有条理并且可能更快。
最佳答案
你能把脚本引用放在你的母版页中吗?这样它将可用并使它变得容易得多。
关于c# - 路由问题(.NET 而不是 MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8166726/