【发布时间】:2011-11-17 11:58:52
【问题描述】:
我在我的 .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;
}
}
我不认为代码被调用,因为在“字符串文件名...”行中放置一个断点永远不会命中。
奇怪的是,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# asp.net .net .net-4.0 routing