首页 文章

限制访问Asp.net MVC中的注册用户

提问于
浏览
3

我有一个asp.net mvc应用程序 . 除了登录页面(Annonymous)之外,只有在身份验证(Authorize属性)之后,才能在asp.net mvc应用程序中访问所有页面 . 在登录页面中,我们有新用户的注册链接 . 如何将“注册”链接限制为仅对特定用户或特定角色可访问 .

我们不希望每个人都使用“注册”页面来创建用户名和密码 .

如何通过ASP.NET MVC授权实现这一点 . 我们在应用程序中使用标准SQL成员资格和角色提供程序 .

1 回答

  • 4

    Making sure a user is logged in to gain access to a view

    完成此操作的最简单方法是使用控制器操作方法上方的Authorize属性 . 例如,我们只希望允许用户在已经登录到站点时更改密码 . 为了防止未经授权的用户访问更改密码视图,我们可以限制访问,如下所示:

    [Authorize]
    public ActionResult ChangePassword()
    {
        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        return View();
    }
    

    您也可以通过检查User对象手动完成此操作,如下所示:

    public ActionResult ChangePassword()
    
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("LogOn", "Account");
    
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }
    

    Making sure a user is in a particular role to gain access to a view

    您可能有一些只应该可以访问特定角色的用户的视图 . 这也可以使用Authorize属性完成,如下所示:

    [Authorize(Roles = "Administrator")]
    public ActionResult Index()
    {
        return View();
    }
    

    您也可以使用以下方法在代码中完成此操作:

    public ActionResult Index()
    {
        if (!User.IsInRole("Administrator"))
            return RedirectToAction("LogOn", "Account");
    
        return View();
    }
    

    reference: Using our Role and Membership Providers

相关问题