10

我正在尝试在我的 Web 应用程序中实现基于角色的授权,如下所示:

[HttpPost]
[ActionName("Login")]
public ActionResult Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        string userName = model.Username;
        string[] userRoles = (string[])Session["UserRoles"];

        ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

        userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

        identity.AddClaim(new Claim(ClaimTypes.Name, userName));

        AuthenticationManager.SignIn(identity);

        return RedirectToAction("Success");
    }
    else
    {
        return View("Login",model);
    }
}

我在两行出现错误:

1.ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

和:

2.AuthenticationManager.SignIn(identity);

错误1:

the name 'DefaultAuthenticationTypes' does not exist in the current context

错误2是:

Authentication manager does not contains definition for SignIn

我试图找到一个解决方案如何实现这一点,但我找不到与错误相关的任何内容。

4

2 回答 2

10

DefaultAuthenticationTypes是身份框架的一部分,可以在Microsoft.AspNet.Identity命名空间中找到。

要使用它,using请在文件顶部添加一个

using Microsoft.AspNet.Identity;
//...other code
identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

或者直接调用

identity = new ClaimsIdentity(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

第二个问题已经在您的另一个问题中处理

于 2016-10-28T14:19:34.670 回答
2

首先,它只是一个常量字符串

如果您不想安装软件包,最快(而且不是很正统)的解决方案是

ClaimsIdentity identity = new ClaimsIdentity("ApplicationCookie");

你可以在这里看到定义

于 2019-02-07T10:16:47.627 回答