ASP.NET MVC and ReturnUrl


I’ve seen many ASP.NET MVC samples and some of them do not honor the ReturnUrl parameter, rendering this unusable.

Classic ASP.NET has the login form component that puts the same exact URL used to access the login page in the form action URL, preserving the ReturnUrl parameter and then, FormsAuthentication.GetReturnUrl() gets it from the Request.QueryString collection.

Fortunately, the GetReturnUrl() method looks as well in Request.Form in case there’s nothing in the query, this way, we can use a hidden field as well to store the ReturnUrl in the View and pass it through POST when the login form is submitted.

So, in ASP.NET MVC we have two options:

  • Use simply Html.BeginForm() without parameters, which will put a simple form tag, with the same URL as the current one and use POST by default
  • If we want to have more control on the Html.BeginForm(), put a hidden field with the value of the ReturnUrl, only if the ReturnUrl is not empty, or it will fail. This can be obtained from the Request.QueryString collection, the ViewData if we put it previously on the Controller action or even better store it in the ViewModel and have a strong typed reference.

And that’s it. Then, FormsAuthentication.GetReturnUrl() will get the proper URL and other methods like FormsAuthentication.RedirectFromLoginPage() will also work seamlessly.

Related Posts

Bye bye Kurobox

A deserved farewell to a device that has worked flawlessly for so many years

DIY Arduino Christmas tree lights

A detailed explanation of my home made light switcher made with Arduino and a relay shield

Back to blogging

My statement on getting back to blogging. Will this go anywhere?

Lessons learned optimizing MySQL

A summary of some things I discovered while trying to optimize the performance of a production MySQL server.

Simple Mini Profiler Glimpse plugin

I just created my first Glimpse plugin, integration between Mininprofiler and Glimpse.

Carbon Copy Cloner saved my day

Just a gratitude post because this piece of software was extremely useful when others don't. And it was my birthday.

Troubleshooting MSDTC, RPC and NServiceBus issues

MSDTC is rare and can cause many headaches. This is the process I followed to track down the problems I was having

Using fail2ban with nginx in Debian

fail2ban helps you fight spam and bots but comes with an Apache sample. I converted it to handle Nginx information.

How msiinv saved my day

mssinv is a tool to manage MSI installed packages and I used it to track a problem with a package partially installed, that had to be removed with this tool

Install ASP.NET MVC 3 Manually

Due to some strange problems in my PC, I had to install this package manually and this is applicable to many other installers