简体   繁体   中英

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.

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" />

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