How to redirect users who are either not logged in to the login page in C # MVC 4.5 if they try to access other pages of the site at the URL

I have one website on which I want users to be redirected to the Login page if they are not logged in. Users can try to access web pages by posting a URL. I want to do this in C # MVC 4.5

Here I do not want the "[Authorize]" action to be available if it is not signed. This is an index action to view the index page.

//Login Controller [AllowAnonymous] public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(FormCollection frm) { ....//other code } [Authorize] public ActionResult Index() { List<DTO> obj = objConfigurator.GetDataList(); return View(obj); } public ActionResult Edit(int Id) { DTO obj = objC.GetListById(Id); return View(obj); } 
+5
source share
1 answer

Use the [Authorize] attribute on your controller.

 [Authorize] public class YourController: Controller { . . . [AllowAnonymous] public ActionResult Register() { } [AllowAnonymous] public ActionResult LogIn() { } . . . } 

In addition, you must add your login page to web.config -

 <system.web> <authentication mode="Forms"> <forms loginUrl="~/Login" timeout="2880" /> </authentication> </system.web> 

You have another better option for registering AuthorizeAttribute as a global filter in the global.asax file.

 public static void RegisterGlobalFilters(GlobalFilterCollection filters) { .... filters.Add(new System.Web.Mvc.AuthorizeAttribute()); } 

Therefore, you should only apply [AllowAnonymous] to the actions that you want to be visited by anonymous users.

+10
source

Source: https://habr.com/ru/post/1214535/


All Articles