Search code examples
c#asp.netvisual-studio-2013url-mapping

URL Mapping - Change Default.aspx to virtual page after first page load


i want to have virtual page instead of Default.aspx like :
www.mydomain.com/Default.aspx -> www.mydomain.com/Virual-Page
after opening my url in browser.

How could i change web.config to get that goal?

The codes below in web.config does not work....

<urlMappings enabled="true">
  <add url="~/Virtual-Page" mappedUrl="~/Default.aspx"/>
</urlMappings>

Solution

  • you need this package: ASP.NET Friendly URL's how to implement can be found on Hanselman's Blog

    Add this to your global.asax file

    void Application_Start(object sender, EventArgs e)
    {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
    

    Add a reference at the top of the Global.asax file as shown below:

    using System.Web.Routing;
    

    this automatically rewrites your URL.

    If you want to keep default.aspx, use the URL Mapping:

    <urlMappings enabled="true">
        <add url="~/Virtual-Page" mappedUrl="~/default.aspx" />
    </urlMappings>
    

    Add a rewrite rule to redirect your base URL, with URL Rewrite

    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Rewrite to Virtual-Page">
            <match url="(.*)" />
            <action type="Redirect" url="~/Virtual-Page" redirectType="Permanent" />
          </rule>
        </rules>
        </rewrite>
      </system.webServer>
    

    If you can't use URL rewrite add a response.redirect in the global.asax begin request:

    void Application_BeginRequest(object sender, EventArgs e)
        if (!HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://localhost/Virtual-Page"))
        {
                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString().ToLower().Replace("http://localhost/", "http://localhost/Virtual-Page"));
        }