Registration method with Identity on an empty project

▼魔方 西西 提交于 2020-01-06 14:04:42

问题


I'm working in an empty MVC entity framework with ASP.NET Identity project, trying to finish a Register method for an IdentityController that handle all user related operations.

The problem is that when trying to login with SignInAsync method after creating the user, the system doesn't find the references to work with that method.

So, on the following code snippet...:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebApplication.Models;

namespace WebApplication.Controllers
{
    public class IdentityController : Controller
    {
        UserManager<IdentityUser> UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new WebApplicationIdentityDbContext()));
        RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new WebApplicationIdentityDbContext()));

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel credential)
        {
            if (ModelState.IsValid)
            {
                if ((await UserManager.CreateAsync(new IdentityUser { UserName = credential.Name }, credential.Password)).Succeeded)
                {
                    await SignInAsync(User, false);

                    return RedirectToAction("Index", "StartupController");
                }
            }
            return View();
        }
    }
}

...what is missing?


回答1:


That's because it's not a framework method. It's just something the team added to the generated AccountController. Here's the code from my AccountController. I've modified mine a bit, but I think this is what the original looked like:

private async Task SignInAsync(User user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}


来源:https://stackoverflow.com/questions/21564260/registration-method-with-identity-on-an-empty-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!