Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily redirect if not authenticated in MVC 3?

Tags:

I am brand new to ASP.NET, and I'm trying to find a way to easily redirect an unauthenticated user from any page on the site to the logon page. I would prefer to not put the following code in every HTTP GET function if there is another option.

if (!Request.IsAuthenticated) {      return RedirectToAction("LogOn", "Account"); } 
like image 725
blachniet Avatar asked Jul 21 '11 02:07

blachniet


People also ask

How does MVC handle wrong URL?

If those URLs don't include a controller or action method name, then you can provide the missing information through default values on your routes. But if those URLs include an incorrect action or controller name, then ASP.NET MVC will simply return one of the standard HTTP error codes.

What is the difference between redirect and RedirectToAction in MVC?

RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.


1 Answers

Mark your controller with [Authorize] attribute http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

See your web.config, by default you should have Forms authentication turned on authentication mode="Forms" http://msdn.microsoft.com/en-us/library/eeyk640h.aspx

Also look at this question ASP.NET MVC Authorization

In case if you want to have custom Authorize behavior look here Customizing authorization in ASP.NET MVC

like image 163
angularrocks.com Avatar answered Oct 05 '22 22:10

angularrocks.com