Jerry Dodge Jerry Dodge - 1 month ago 11
ASP.NET (C#) Question

Problems using query strings when hiding page extension

I'm using ASP.NET with C# (Visual Studio 2015). I've implemented the following code snippet in the

Global.asax
file:

void Application_BeginRequest(object sender, EventArgs e)
{
//Removes requirement of having ".aspx" in the URL
String WebsiteURL = Request.Url.ToString();
String[] SplitedURL = WebsiteURL.Split('/');
String[] Temp = SplitedURL[SplitedURL.Length - 1].Split('.');

// This is for aspx page
if (!WebsiteURL.Contains(".aspx") && Temp.Length == 1)
{
if (!string.IsNullOrEmpty(Temp[0].Trim()))
Context.RewritePath(Temp[0] + ".aspx");
}

}


So that instead of forcing an extension in the page URL:


http://www.example.net/SomePage.aspx


I can leave out the extension to redirect to the same page:


http://www.example.net/SomePage


The problem is that now if I add a query string to the URL, it can no longer find the page. For example:


http://www.example.net/SomePage?name=value


results in a 404 Not Found error.

How can I make query strings work even when the extension is hidden?

Answer
    void Application_BeginRequest(object sender, EventArgs e)
{
//Removes requirement of having ".aspx" in the URL
    Uri uri = this.Request.Url;
    string path = uri.AbsolutePath;
    string query = uri.Query;
    string[] seg = path.Split('.');
    if (seg.Length == 1)
    {
        path = path + ".aspx";
          string url = path + query;
          Context.RewritePath(url);
    }
 }   

Try the above code. As VDWWD mentioned, the best approach is use IIS url rewriter instead.