[英]URL Rewriting exceptional case for removing .aspx extension
我的情況是:我有一個ASP.NET WebForm網站。 用戶可以在我的網站上創建自己的頁面,其頁面URL類似於以下內容:(MyWebsite.com/UserPage)。 但實際上是:(MyWebsite.com/UserPages.aspx?q=UserPage)。 這意味着當您輸入URL(MyWebsite.com/UserPage)時,它將重寫URL並顯示(MyWebsite.com/UserPages.aspx?q=UserPage)(但地址欄始終類似於(MyWebsite.com/UserPage)。這是我的“ UrlRewriting”類中的代碼:
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (app.Request.Path.Contains("/") && !app.Request.Path.Contains(".") && app.Request.Path.IndexOf("/") == app.Request.Path.LastIndexOf("/"))
{
string userPageTitle = app.Request.Path.Substring(app.Request.Path.IndexOf("/") + 1);
if (!string.IsNullOrEmpty(userPageTitle ))
{
app.Context.RewritePath(string.Format("UserPages.aspx?q={0}", userPageTitle));
}
}
}
現在這是我的問題:正如我說我的項目是ASP.NET WebForm,(因此,所有頁面都具有.aspx擴展名),我想刪除Urls中的.aspx擴展名,我已經嘗試了web.config中的一些代碼,正常工作(在正常情況下),但對於我來說,如果輸入(MyWebsite.com/UserPage),它將把該“ UserPage”視為“ UserPage.aspx”。 我該如何處理?
我通常使用ASP.NET Web Forms 4+中可用的路由來做到這一點。
您在Global.asax
注冊路由(URL模式),並指定哪個ASPX頁面將處理該URL。
此示例將讓UserPage.aspx處理所有其他ASPX頁面無法處理的URL。
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("UserPageRoute", "{*url}", "~/UserPage.aspx");
}
然后,在UserPage.aspx
,可以通過查看Request.Url
對象來確定請求的URL,例如。 Request.Url.PathAndQuery
。
請注意,您可能需要一些額外的web.config
設置才能起作用,例如(以管理無擴展名的URL請求)...
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.