ASP.NET Login Control & ReturnUrl Problem
I was surprised today by an odd behavior of Login control. When browsing some pages in my web site that required authentication, I was redirected to the Login page, but then, after successful login, I was redirected to the page, specified by DestinationPageURL property of Login control (instead of original URL). I went to investigate. Here are the results:
First of all Login control standard behavior:
If the user browse the Login page directly, after login, asp.net will redirect the user to page which is defined by DestinationPageURL property. If the DestinationPageURL property is empty, the default value is default.aspx. If the user browse another page but is redirected to the Login.aspx for being not authorized, then after login, asp.net will redirect the user to page which the user originally wants to access. In this situation, DestinationPagURL property is ignored. Login control uses ReturnUrl query string parameter to locate original page.
The situation on my site:
It is a bit more complex. The site actually has two completely different login pages. One of them defined as Login page in Web.config. In some cases users (depending on referrer and cookies) redirected from main login page to the secondary login page, which also has Login control.
It appears that Login control behaves slightly different in this scenario. If page is not defined as Login page in configuration file, ReturnUrl parameter is ignored completely. Login control try to redirect user to the page specified by DestinationPageURL property. If DestinationPageURL property not set, page that hosts Login control simply being reloaded, using the same URL.
Knowing all this, the solution come easily:
On the secondary login page I add flowing lines to the Page_Load method:
string returnUrl = Request.Params["ReturnUrl"];
if (!String.IsNullOrEmpty(returnUrl))
Login1.DestinationPageUrl = returnUrl;