AuthenticationManager类中不存在AuthenticationManager.SignIn()

时间:2016-10-28 13:28:25

标签: c# asp.net asp.net-mvc authentication

我正在尝试使用AuthenticationManagerSignIn();

中的方法

以下是我的表现:

AuthenticationManager.SignIn(identity);

但它说那里SignIn不存在......

AuthenticationManager的路径是:

System.Net.AuthenticationManager

我在这里遗漏了什么吗?

编辑:这是控制器的迷你版本:

using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Linq;
using System.Security.Claims;
using System.Web.Mvc;
using WebApplication2.Models;
using WebApplication2.ViewModels;

[HttpPost]
[ActionName("Login")]
public ActionResult Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        string userName = (string)Session["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);
    }
}

编辑:出现了新的错误:

The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.

1 个答案:

答案 0 :(得分:5)

使用IAuthenticationManager

的控制器的简化示例
using Microsoft.Owin.Security;
using System.Web;    
//...other usings

public class AccountController : Controller {

    [HttpPost]
    [ActionName("Login")]
    public ActionResult Login(LoginViewModel model) {
        if (ModelState.IsValid) {
            string userName = (string)Session["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);
        }
    }

    private IAuthenticationManager AuthenticationManager {
        get {
            return HttpContext.GetOwinContext().Authentication;
        }
    }    
}