Dan Nick Dan Nick - 12 days ago 5
ASP.NET (C#) Question

HttpContext.Current.Request.Url.AbsolutePath with Master Page

I am using HttpContext.Current.Request.Url.AbsolutePath as part of my security which the user needs to login before they access certain pages.

In this example and it works great. The user has to sign in before they view their profile.

if (Session["UserID"] == null)
{
Response.Redirect("Login.aspx/?ReturnURL=" + HttpContext.Current.Request.Url.AbsolutePath);
}


The end result looks like this:

http://localhost:54324/Login.aspx/?ReturnURL=/Profile_Page.aspx


The issue I am having is the pages are part of the master page. When the redirect occurs to the login page, nothing on the master page works. The navigation links do not fire, the images show broken links, etc. However when I access the Login Page directly everything in the master page works fine.

Answer

There's an extra forward slash in your redirect URL:

Response.Redirect("Login.aspx/?ReturnURL=" + HttpContext.Current.Request.Url.AbsolutePath);
                             ^

Your login page still loads correctly because ASP.NET treats the slash as a separator for additional path information, similar to the way that a question mark is the separator for the query string.

But the extra slash causes a browser to resolve relative URLs for links and images relative to a child directory named Login.aspx instead of relative to the root of your application. For example, if you had the image <img src="Logo.png">, a browser would attempt to load Login.aspx/Logo.png. Removing the forward slash should fix the problem with the redirect:

Response.Redirect("Login.aspx?ReturnURL=" + Request.Url.AbsolutePath);

Nevertheless, visitors will still get broken URLs if they manually append the slash. To avoid this, use the built-in <asp:HyperLink> and <asp:Image> server controls, which will generate relative URLs taking the extra slash into account:

<asp:HyperLink runat="server" NavigateUrl="~/About.aspx" Text="About Us" />
<asp:Image runat="server" ImageUrl="Logo.png" />