【发布时间】:2011-11-03 04:50:20
【问题描述】:
我正在通过 Global.asax 使用路由。
我希望http://www.website.com/ad/123 引导至http://www.website.com/ad.aspx?id=123
这很好用:
routes.MapPageRoute("AdById", "ad/{cid}", "~/ad.aspx");
我不得不“取消路由” js 和 css 文件和图像,所以我有一些处理程序:
routes.Add("AdImagesRoute", new Route("ad/graphics/{filename}.{ext}", new ImageRouteHandler()));
routes.Add("AdJSRoute", new Route("ad/scripts/{filename}.js", new JSRouteHandler()));
routes.Add("AdCSSRoute", new Route("ad/styles/{filename}.css", new CSSRouteHandler()));
现在我还想“装饰” URL,所以我想要这样的东西:
http://www.website.com/ad/123/House%20For%20Sale
也导致http://www.website.com/ad.aspx?id=123
所以我添加了这个:
routes.MapPageRoute("AdByIdWithBlah", "ad/{cid}/{blah}", "~/ad.aspx");
但现在的问题是,当客户端访问此 url:http://www.website.com/ad/123 时,会请求像 http://www.website.com/ad/scripts/scriptfile.js 这样的 javascript,这使得路由认为它是一个广告号和一些“废话”并重定向到 ad.aspx。
所以我需要以某种方式告诉路由,如果 cid 不是数字(因为它是一个文件夹)或 blah 以 .js 或 .css 结尾,则不要路由。
我试过了:
Route adwithblahroute = new Route("ad/{cid}/{blah}", new RouteValueDictionary() {{"blah", "blah"}} , new RouteValueDictionary() { { "cid", @"^\d+$" }, {"blah", @"^[^.]$"} }, new BlahRouteHandler());
routes.Add(adwithblahroute);
但现在如果我请求 http://www.website.com/ad/123/sometext,我会得到 404
希望有人能帮我解决这个问题。
---- 编辑----
顺便说一句,这是 BlahRouteHandler:
public class BlahRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
int cid = 0;
string filepath;
if (Int32.TryParse(requestContext.RouteData.Values["cid"] as string, out cid))
{
filepath = requestContext.HttpContext.Server.MapPath("~/ad.aspx");
requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();
}
else
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.StatusCode = 404;
requestContext.HttpContext.Response.End();
}
return null;
}
}
----- 已添加 ------
对于 Google 的人,我找到了一种单行解决方案,我不需要处理程序或类,看起来。这条线成功了:
routes.MapPageRoute("AdByIdWithBlah", "ad/{cid}/{blah}", "~/ad.aspx", false, new RouteValueDictionary() { { "blah", "blah" } }, new RouteValueDictionary() { { "cid", @"^\d+$" } } );
【问题讨论】: