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

Ven*_*nki 3 asp.net asp.net-mvc-3

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

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

使用ASP.NET MVC授权怎么可能。我们在应用程序中使用标准的SQL成员资格和角色提供程序。

bot*_*bot 5

确保用户已登录才能访问视图

最简单的方法是使用控制器的操作方法上方的Authorize属性。例如,如果用户已经登录到站点,我们只希望允许他们更改其密码。为了防止未经授权的用户访问更改密码视图,我们可以这样限制访问:

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

您还可以通过像这样检查User对象来手动完成此操作:

public ActionResult ChangePassword()

    {
        if (!User.Identity.IsAuthenticated)
            return RedirectToAction("LogOn", "Account");

        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        return View();
    }
Run Code Online (Sandbox Code Playgroud)


确保用户处于特定角色中以获得对视图的访问权限

您可能有一些视图,只有特定角色的用户才能访问这些视图。这也可以使用Authorize属性来实现,如下所示:

[Authorize(Roles = "Administrator")]
public ActionResult Index()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

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

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

    return View();
}
Run Code Online (Sandbox Code Playgroud)

参考:使用我们的角色和成员资格提供者