asp.net MVC和检查,如果用户登录 [英] asp.net mvc and check for if a user is logged in

查看:117
本文介绍了asp.net MVC和检查,如果用户登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net mvc的新的,我需要检查,如果用户登录或没有在我的应用程序,所以我把我的Global.asax下面这段code的

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.

推荐答案

你需要做这种方式?您应该检查,如果你可以使用asp.net认证,授权和会员供应商。 (当你做出新的ASP.NET MVC 3应用程序,他们会自动生成[当你离开了互联网应用检查])。

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]).

您可以再使用标注为控制器和行动:(伪code):结果
这将允许访问控制器只有授权用户(你甚至可以指定哪些角色被允许哪些用户或):[授权(角色=管理员)]

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{.....}

和检查,如果用户登录,已经有与身份属性的用户属性。结果
这code检查,如果用户进行身份验证(登录):

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) ...
...
}

这篇关于asp.net MVC和检查,如果用户登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆