asp.net mvc并检查用户是否已登录

ano*_*uar 4 security asp.net-mvc global-asax

我是asp.net mvc的新手,我需要检查用户是否在我的应用程序中登录,所以我将以下代码放在我的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");
            }                
        } 
    }
Run Code Online (Sandbox Code Playgroud)

我拦截每个传入的请求进行检查我想知道是否还有其他方法可以做这种工作并提前感谢.

Dam*_*amb 24

你需要这样做吗?您应该检查,如果您可以使用asp.net身份验证,授权和成员资格提供程序.(当您创建新的ASP.NET MVC 3应用程序时[当您选中"Internet应用程序"时),它们会自动生成).

然后,您可以对控制器和操作使用注释:(伪代码):
这允许仅向授权用户访问控制器(您甚至可以指定允许哪些用户或哪些角色):[授权(角色="管理员")]

[Authorize]
controller{.....}
Run Code Online (Sandbox Code Playgroud)

要检查用户是否已登录,已存在具有Identity属性的User属性.
此代码检查用户是否已通过身份验证(已登录):

controller...() {
...
if (User.Identity.IsAuthenticated) ...
...
}
Run Code Online (Sandbox Code Playgroud)