c# - 充分利用具有 n(3) 层架构的 MVC Owin 标识

标签 c# asp.net-mvc entity-framework asp.net-identity

我一直在开箱即用地学习 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/

相关文章:

c# - 家庭 Controller 中每个 mvc actionresult 的代码相同

c# - 不能将重复值插入到唯一索引中(但是...)

c# - 带有可选参数的 Entity Framework ?

c# - 自动保存动态创建的控件的最佳方法?

通过泛型实现的 C# 参数化属性类?

c# - 导入构造函数和子类

c# - 从用户输入中获取查询

c# - Kentico 页面类型转换迭代显示

asp.net-mvc - 我可以将匿名类型传递给我的 ASP.NET MVC View 吗?

javascript - 使用 AJAX/jQuery 将 SelectList 获取到 MVC View