c# - MVC 5 登录自定义数据库

标签 c# asp.net-mvc-5 owin asp.net-mvc-5.1

我正在从 mvc 3 切换到 mvc 5,我知道他们更改了 .Net 4.5.1 中的身份验证(OWIN 身份验证)。

我只需要它来登录网站,以便 Request.IsAuthenticated 为真,我不想要 Microsoft 的成员(member)资格,我想使用我的数据库。

我试过的连这个都不行

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Name"));
claims.Add(new Claim(ClaimTypes.Email, "mail@mail.com"));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

var ctx = HttpContext.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(identity);

我真的不知道该怎么做,但我想使用我自己的数据库登录系统,只有用户名和密码

最佳答案

试试这个,希望对你有帮助。

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = MyViewModels.checkUser(model.UserName, model.Password);
            if (user!=null)
            {
                SignInAsync();
                return RedirectToAction("Welcome");
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }
        return View(model);
    }

    private void SignInAsync()
    {
        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Name, "UserName"));
        claims.Add(new Claim(ClaimTypes.Email, "User@mail.com"));
        var id = new ClaimsIdentity(claims,
                                    DefaultAuthenticationTypes.ApplicationCookie);

        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignIn(id);
    }

    [Authorize]
    public ActionResult Welcome()
    {
        return View();
    }

如果你在 Action 中添加[Authorize]属性,那么它只会重定向用户名和密码是授权

从数据库中获取用户名和密码的函数

    public static UserTable checkUser(string userName, string password)
    {
        DemoEntities db = new DemoEntities();
        var query = (from u in db.UserTables
                     where u.UserName == userName && u.Password == password
                     select u).FirstOrDefault();
        if(query!=null)
            return query;
        else
            return null;
    }

关于c# - MVC 5 登录自定义数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21658725/

相关文章:

c# - 我可以从我的 Windows 10 UWP 应用程序引用 .NetStandard 库吗?

c# - Kendo Grid 内联编辑日期格式问题

entity-framework - 在 ASP.NET MVC5 Identity 系统中进一步扩展 ApplicationUser 类

javascript - 等待 form.submit()/POST 完成

c# - 简单注入(inject)器使用 OWIN 在 WebAPI 中获取当前主体

c# - 异步 TCP 操作期间的 AccessViolation

c# - 如何在 WebBrowser 控件中注入(inject) Javascript?

javascript - 在单个表行旁边显示确认消息

asp.net - 在 MVC5 应用程序中使用 OWIN 包的好处

mysql - 使用 Hangfire 进行自动付款处理