2017-08-27 31 views
1

HttpContextBase不包含Authentication的定义,并没有扩展方法Authentication接受HttpContextBase类型的第一个参数可以找到(是否缺少using指令或程序集引用...HttpContextBase”不包含用于定义‘在MVC认证’

我曾尝试另一种方式,但它显示上面的错误...... HttpContext.SignInAsync。我使用VS 2017年

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> DangNhap(LoginViewModel model, string returnUrl) 
    { 
     if (!ModelState.IsValid) 
     { 

      return View(model); 
     } 

     //TODO : Do something to authenticate the user 
     if (model.Username == "Admin" && model.Password == "admin") 
     { 
      var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); 
      identity.AddClaim(new Claim(ClaimTypes.Name, model.Username)); 

      await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
       new ClaimsPrincipal(identity)); 

      return RedirectToLocal(returnUrl); 
      //var result = 
      // await SignInManager.PasswordSignInAsync(model.Username, 
      //  model.Password, true, shouldLockout: false); 

      //switch (result) 
      //{ 
      // case SignInStatus.Success: 
      //  return RedirectToLocal(returnUrl); 
      // case SignInStatus.Failure: 
      // default: 
      //  ModelState.AddModelError("", "Invalid login attempt."); 
      //  return View(model); 
      //} 

     } 
     else 
     { 
      ModelState.AddModelError("Errors", "Username và password sai, hãy đăng nhập lại"); 
      return View(model); 
     } 
    } 
+0

在这行你有没有错误? – CodeNotFound

+0

await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); – KSon

+0

检查是否安装并正确引用了'Microsoft.Owin.Security'&'Microsoft.Owin.Host.SystemWeb'软件包(尝试使用'System.Web.HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity)); '而不是在控制器动作中使用'HttpContext'属性)。 –

回答

1

我得到这个固定由HttpContext的直接访问SignInAsync方法。

尝试如下访问它:

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
      new ClaimsPrincipal(identity)); 

注意:您可以直接作为上述仅在控制器类来访问。

你不需要任何Owin包。如果有的话,请将其卸载。为了实现cookie认证,安装以下两个包就足够了。

  • Microsoft.AspNetCore.Authentication
  • Microsoft.AspNetCore.Authentication.Cookies