简体   繁体   中英

URL Rewriting exceptional case for removing .aspx extension

My scenario is: I have a website which is ASP.NET WebForm. Users can create their own page on my web site, their page url would be something like this: (MyWebsite.com/UserPage). but It is actually: (MyWebsite.com/UserPages.aspx?q=UserPage). It means when you enter the url (MyWebsite.com/UserPage) It rewrites the url and shows you (MyWebsite.com/UserPages.aspx?q=UserPage) (but the address bar is always like (MyWebsite.com/UserPage). Here's my code in my "UrlRewriting" class:

    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));
            }
        } 
   }

Now here's my problem: as I said my project is ASP.NET WebForm, (So, all of pages have .aspx extension) I wanted to remove the .aspx extension in my Urls, I've tried some codes in web.config which were working properly (In normal cases), but In my case, if you enter (MyWebsite.com/UserPage) It will be considering this "UserPage", as "UserPage.aspx". How can I handle this?

I usually do this with Routing which is available in ASP.NET Web Forms 4+.

You register your routes (URL patterns) in Global.asax , and specify which ASPX page will handle that URL.

This example would have UserPage.aspx handle all URLs that weren't otherwise handled by other ASPX pages.

void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapPageRoute("UserPageRoute", "{*url}", "~/UserPage.aspx");
}

Then in your UserPage.aspx you can determine the URL requested by looking at the Request.Url object, eg. Request.Url.PathAndQuery .

Note that you may need some extra web.config settings for this to work, eg (to manage extensionless URL requests)...

<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM