gpt4 book ai didi

c# - AuthenticationManager.SignIn() 不存在于 AuthenticationManager 类中

转载 作者:太空狗 更新时间:2023-10-29 20:23:12 25 4
gpt4 key购买 nike

我正在尝试使用 AuthenticationManagerSignIn() 中的方法;

这是我的做法:

AuthenticationManager.SignIn(identity);

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

AuthenticationManager 的路径是:

System.Net.AuthenticationManager

我是不是漏掉了什么???

编辑:这是 Controller 的迷你版:

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.

最佳答案

使用 IAuthenticationManager 的 Controller 简化示例

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

关于c# - AuthenticationManager.SignIn() 不存在于 AuthenticationManager 类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com