当前上下文中不存在名称为“DefaultAuthenticationTypes”的内容。

11

我正试图像以下这样在我的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

我一直在努力寻找如何实现这个问题的解决方案,但是我没有找到任何与错误有关的内容。

2个回答

10

DefaultAuthenticationTypes是Identity框架的一部分,位于Microsoft.AspNet.Identity命名空间中。

要使用它,请将using添加到文件顶部。

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

或直接拨打电话

identity = new ClaimsIdentity(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
第二个问题已经在你的另一个问题中处理过了,链接在这里: here

2

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

如果您不想安装软件包,最快(但不太正统)的解决方案是:

Original Answer翻译成"最初的回答"

ClaimsIdentity identity = new ClaimsIdentity("ApplicationCookie");

你可以在这里查看“最初的回答”的定义:这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接