asp.net-mvc-5returnurl

Can we set return Url at central level in mvc 5 after login?


Is there any provision like, say for visitor user of web application. he is doing say search or trying any functionality, which is allowed for the visitor user and at certain action need to be logged in and if has no credential then need to sign up and return back to the same action page where he was before login/sign up. Is it possible to handle this at application or session level in mvc 5?


Solution

  • Yes, this is handled for you out of the box when you create a new ASP.NET MVC Project. To try this, do the following:

    1. Create a new ASP.NET MVC 5 Project.
    2. Open the Home Controller, and place an [Authorize] Attribute above the "About" action.
    3. Navigate to the "About" menu option at /About.
    4. You will automatically be redirected to the login page. Note that the login URL now reads "/Account/Login?ReturnUrl=%2FHome%2FAbout". This is how the initiating URL is passed into the login page.
    5. Log into the site. After logging in, note that you are redirected back to the "/About" page that you were trying to initially access.

    Of course this is not bullet proof. If you try to register before logging in you will notice that you are no longer redirected back to that initial page, but it is a start.