Asp.net MVC4,如何在不使用任何提供程序的情况下使用Role

时间:2013-01-07 21:20:59

标签: asp.net asp.net-mvc-4

我想在asp.net MVC4项目中使用没有任何提供者的角色。

我成功地在没有提供者的情况下登录和退出。

但是对于这个角色,我不知道如何设置它。

这是我对AccountController.cs的一部分

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && myLogin(model.UserName, model.Password, persistCookie: model.RememberMe))
    {
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

    //set Roles, how can I set role to users?
    if (HttpContext.User != null)
    {
        if (!Roles.RoleExists("Administrator"))
        {
        Roles.CreateRole("Administrator");
        }
        Roles.AddUserToRole(model.UserName, "Administrator");

        //string[] roles = { "Moderator", "Administrator" };
        //HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, roles);
    }

    return RedirectToLocal(returnUrl);
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}

private bool myLogin(string userName, string password, bool persistCookie)
{
    if (userName == "root" && password == "root")
    {
    return true;
    }
    else
    {
    return false;
    }
}

// set Roles部分不起作用,错误信息说,

未找到名称为“root”的用户。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。 异常详细信息:System.InvalidOperationException:未找到名为“root”的用户。

的Web.config

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <roleManager enabled="true" />

我想控制使用角色检查

访问此页面
[Authorize(Roles="Administrator")]
public ActionResult Contact()
{
      ViewBag.Message = "Your contact page.";
      return View();
}

如何为用户定义角色?在Action上使用过滤器?

1 个答案:

答案 0 :(得分:4)

当您呼叫Roles.*时,您基本上正在调用在web.config中注册的基础角色提供程序。如果您不想使用默认角色提供程序(适用于SQL Server),则始终可以write a custom role provider

您需要做的就是编写RoleProvider类的自定义实现,或者至少编写您打算使用的方法:

public class MyRoleProvider: RoleProvider
{
    ... your implementation comes here
}

然后在web.config中注册自定义角色提供程序以替换默认角色:

<roleManager defaultProvider="DefaultRoleProvider">
    <providers>
        <add name="DefaultRoleProvider" type="MyNamespace.MyRoleProvider, MyAssembly" />
    </providers>
</roleManager>