我一直在开箱即用地学习 Owin Identity我喜欢它为我们提供的用户管理的易用性。然后我遇到的问题是它通过我不想要的 ApplicationDbContext
直接与 EF 交互(表面上)。我更愿意使用我的 3 层架构,IE 它与服务层 (BLL) 交互,服务层与 EF 交互。我找不到模板、教程甚至起点来维护所提供的所有功能并实现我想要的分离。
那么有没有一种方法可以使用服务层来代替 MVC Identity 包中的 ApplicationDbContext
。
最佳答案
如果您想使用现有的数据库/表,则不必使用整个 ASP.Net Identity。相反,您可以只使用 Owin Cookie 身份验证中间件。
我在 GitHub 有可用的示例代码.如果要测试它,只需在 AccountController.cs 处设置一个断点即可。 ,并返回真值。
下面主要是配置中间件和登录两个类。
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
}
OwinAuthenticationService.cs
public class OwinAuthenticationService : IAuthenticationService
{
private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";
public OwinAuthenticationService(HttpContextBase context)
{
_context = context;
}
public void SignIn(User user)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
public void SignOut()
{
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignOut(AuthenticationType);
}
}
关于c# - 充分利用具有 n(3) 层架构的 MVC Owin 标识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41471014/