問題描述
當使用帶有 Web 窗體的 ASP.NET 4.0 路由來生成將充當某種通配符的路由時,我有一種簡單的方法嗎?
I there a simple way when using ASP.NET 4.0 routing with Web Forms to produce a route that will act as some kind of wildcard?
在我看來,在 WebForms 中,您必須為每個頁面指定一個路由 - 我正在尋找某種通用路由,可以在不需要任何特定內容的情況下使用,也許直接從路徑映射到路徑,所以...
It seems to me that within WebForms, you have to specify a route for every page - I am looking for some kind of generic route that can be used where nothing specific is required, perhaps mapping directly from path to path so...
http://somedomain.com/folder1/folder2/page 可能會映射到文件夾1/folder2/page.aspx
http://somedomain.com/folder1/folder2/page would possibly map to folder1/folder2/page.aspx
有什么建議嗎?
謝謝
推薦答案
你可以像這樣匹配所有剩余的路由:
You can match all remaining routes like this:
routes.MapPageRoute("defaultRoute", "{*value}", "~/Missing.aspx");
在這種情況下,我們知道所有路由,并希望將其他任何內容發送到丟失"/404 頁面.請務必將此作為 last 路由,因為它是一個通配符,可以捕獲所有內容.
In this case, we know all routes, and want to send anything else to a "missing"/404 page. Just be sure to put this as the last route, since it is a wildcard and will catch everything.
您也可以用同樣的方式注冊一個路由,但在內部會映射到一個頁面,如下所示:
Alternatively you could register a route the same way, but internally does mapping to a page, like this:
routes.Add(new Route("{*value}", new DefaultRouteHandler()));
該處理程序類將執行您的通配符映射,如下所示:
That handler class would do your wildcard mapping, something like this:
public class DefaultRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//Url mapping however you want here:
var pageUrl = requestContext.RouteData.Route.Url + ".aspx";
var page = BuildManager.CreateInstanceFromVirtualPath(pageUrl, typeof(Page))
as IHttpHandler;
if (page != null)
{
//Set the <form>'s postback url to the route
var webForm = page as Page;
if (webForm != null)
webForm.Load += delegate { webForm.Form.Action =
requestContext.HttpContext.Request.RawUrl; };
}
return page;
}
}
這在奇怪的地方被打破了一點,以防止水平滾動,但你明白了整體觀點.再次確保這是最后一個路線,否則它將處理您的所有路線.
This is broken a bit in odd places to prevent horizontal scrolling, but you get the overall point. Again, make sure this is the last route, otherwise it'll handle all your routes.
這篇關于asp.net 4.0 網絡表單路由 - 默認/通配符路由的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!