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

て烟熏妆下的殇ゞ 提交于 2019-12-10 13:32:38

问题


I'm trying to implement role-based authorization in my web application like following:

[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);
    }
}

I'm getting an error on two lines:

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

And:

2.AuthenticationManager.SignIn(identity);

The error 1:

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

And error 2 is:

Authentication manager does not contains definition for SignIn

I was trying to find a solution how to implement this but I couldn't find anything related to the errors.


回答1:


DefaultAuthenticationTypes is part of Identity framework and found in Microsoft.AspNet.Identity namespace.

To use it, add a using to the top of the file

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

or call it directly

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

The second issue was already dealt with in another one of your questions here




回答2:


For the first, it is just a constant string

If you do not want to install packages the quickest ( and not very orthodox ) solution is

ClaimsIdentity identity = new ClaimsIdentity("ApplicationCookie");

you can see definition here



来源:https://stackoverflow.com/questions/40304516/the-name-defaultauthenticationtypes-does-not-exist-in-the-current-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!