Tutorial :Redirecting to login page strategy


I have a link on the page that allows the user to perform a certain action if they are logged in. If they are not logged in I want the link to direct them to the login page first. This pretty common. What's the best way to do this? Currently I'm doing this but I don't like it:

<% if(Model.IsUserAuthenticated){ %>  <%= Html.ActionLink("Start Puzzle", "StartPuzzle", "Puzzles")%>  <%} else { %>  <%= Html.ActionLink("Start Puzzle", "Login", "Account")%>  <%} %>  

You get the idea. I don't really like having logic in the view like this. Is it better to just have the "StartPuzzle" action redirect if not logged in?


create htmlhelpers extension method which will check if user is authenticated and return one link or another...something like this:

in your view:


and in you htmlhelper:

if(autorized)  {      return Html.ActionLink("Start Puzzle", "StartPuzzle", "Puzzles");  }  else  {     return Html.ActionLink("Start Puzzle", "Login", "Account");  }  


Here is a good post from Rob Conery about Authentication with MVC using attributes: Authentication and Redirect


That much logic in the view is perfectly fine, IMO. But if there are more than that, or you don't want even that much, then you can have two separate views for logged in and anonymous users and decide which one you're gonna show in the controller. Or have one view and pass the link text and URL from the controller depending on the conditions.


Put an "Authorize" attribute on top of the StartPuzzle action in the controller. This way a non-authenticated user will automatically be redirected to the login page having the returnUrl pointed to what accessed when (s)he was not logged in. This way after a successful login (s)he will be redirected back to the puzzle start.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »