简体   繁体   中英

How to programmatically login to ASP.NET Identity 2?

How do you programmatically login to asp.net identity 2? This is straight forward against Web API, but MVC only project requires __RequestVerificationToken. This is a login method:

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindAsync(model.Email, model.Password);
            if (user != null)
            {
                await SignInAsync(user, model.RememberMe);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

you must create Login View and in that ,submit your data to this method via ajax call. In this case I prefer using jquery.ajax method instead of ajax form . Also create LoginViewModel that contains your user info like username , password so you use strongly typed view .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM