Asp.net mvc and check if the user is registered

I am new to asp.net mvc and I need to check if the user is registered in my application or not, so I put the following code snippet in my global.asax file

void Application_PreRequestHandlerExecute(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; string filePath= context.Request.FilePath; string fileExtention = VirtualPathUtility.GetExtension(filePath); // to skip request for static content like (.css or .js) if (fileExtention == "") { if (filePath.ToLower() != "/account/login") { var user = (Utilisateur)context.Session["USER"]; if (user == null) context.Response.Redirect(@"~/account/login"); } } } 

I intercept every incoming request for verification, I would like to know if there are other ways to do this work and thanks in advance.

+4
source share
2 answers

Do you need to do it like this? You should check if you can use asp.net authentication, authorization and membership services. (They are automatically generated when you create a new ASP.NET MVC 3 application [when you leave the "Internet application" checked]).

Then you can use annotation for controllers and actions: (pseudocode):
This allows access to the controller to authorized users only (you can even specify which users or roles are allowed): [Authorize (Roles = "Administrators")]

 [Authorize] controller{.....} 

And to check if the user is registered, there is already a User property with the Identity property.
This code authenticates the user (logs in):

 controller...() { ... if (User.Identity.IsAuthenticated) ... ... } 
+23
source

Since you mentioned that you have your own β€œmodule” that works with multiple databases, I think you should implement this module as a standard ASP.NET/MVC user membership / authentication provider. Then you can use HttpContext.User.Identity.IsAuthenticated and restrict access to the actions of your controller (or the entire controller) by decorating it with the [Authorize] attribute.

+2
source

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


All Articles