Registration method with Identity on an empty proj

2019-08-29 10:23发布

问题:

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);
}