asp.net mvc and check for if a user is logged in

无人久伴 提交于 2019-12-22 08:57:27

问题


I'm new in asp.net mvc and i need to check if a user is logged in or not in my application so i place the following piece of code in my global.asax

    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 each incoming request to do the checking I'd like to know if there are other ways to do this kind of work and thanks in advance.


回答1:


Do you need to do it this way? You should check, if you can use asp.net authentication, authorization and membership providers. (They are automatically generated when you make new ASP.NET MVC 3 Application [when you leave the 'Internet Application' checked]).

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

[Authorize]
controller{.....}

And to check if user is logged in, there is already User property with Identity property.
This code checks if user is Authenticated (logged in):

controller...() {
...
if (User.Identity.IsAuthenticated) ...
...
}



回答2:


Since you mentioned you have your own "module" that works with several databases, I think you should implement this module as a standard ASP.NET / MVC custom membership/authentication provider. You can then use HttpContext.User.Identity.IsAuthenticated and limit the access to your controller's actions (or the whole controller) by decorating it with [Authorize] attribute.



来源:https://stackoverflow.com/questions/5484786/asp-net-mvc-and-check-for-if-a-user-is-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!