2

This is my DbContext class:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("name=ApplicationDbContext")
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ShopConfiguration());

            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Shop> Shops { get; set; }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

And this is my UserManager class:

public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {

        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext owinContext)
        {
            ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(owinContext.Get<ApplicationDbContext>()));
            return userManager;
        }
    }

This is my Startup class:

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Se crea una instancia del DbContext y el UserManager por 'Request'.
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        }
    }

I have a WebApiBaseController, where the manager and the context is located. All the other controllers inherit from there.

My WebApiBasecontroller:

public class WebBaseApiController : ApiController
    {
        public WebBaseApiController()
        {

        }

        private ApplicationDbContext _dbContext;
        public ApplicationDbContext DbContext
        {
            get { return _dbContext ?? Request.GetOwinContext().Get<ApplicationDbContext>(); }
            private set { _dbContext = value; }
        }

        private ApplicationUserManager _userManager;
        public ApplicationUserManager UserManager
        {
            get { return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
            private set { _userManager = value; }
        }
    }

And this is my Accounts Controller:

public class AccountsController : WebBaseApiController
    {
        [HttpPost]
        public async Task<IHttpActionResult> CreateUser(CreateUserModel userModel)
        {
            if ((await UserManager.FindByNameAsync(userModel.Username)) != null)
                return Content(HttpStatusCode.Conflict, "username_already_exists");
            else if ((await UserManager.FindByEmailAsync(userModel.Email)) != null)
                return Content(HttpStatusCode.Conflict, "email_already_in_use");


            ApplicationUser nUser = CreateUserModel.GenerateContextUser(userModel);

            await UserManager.CreateAsync(nUser, userModel.Password);

            return Created("api/Accounts", userModel);
        }
   }

Now, everytime I make a request to that action, I get this response:

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "El valor no puede ser nulo.\r\nNombre del parámetro: context",
    "ExceptionType": "System.ArgumentNullException",
    "StackTrace": "   en Microsoft.AspNet.Identity.Owin.OwinContextExtensions.GetUserManager[TManager](IOwinContext context)\r\n   en WebApplication4.Controllers.WebBaseApiController.get_UserManager() en C:\\Users\\German Aguilera\\source\\repos\\WebApplication4\\WebApplication4\\Controllers\\WebBaseApiController.cs:línea 29\r\n   en WebApplication4.Controllers.AccountsController.<CreateUser>d__0.MoveNext() en C:\\Users\\German Aguilera\\source\\repos\\WebApplication4\\WebApplication4\\Controllers\\AccountsController.cs:línea 21\r\n--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---\r\n   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   en System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()\r\n--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---\r\n   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   en System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---\r\n   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   en System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---\r\n   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   en System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}

4 hours trying to solve this issue. Any hand? Thanks in advance.

-- EDIT: --

Ok, I found a solution. I replaced:

Request.GetOwinContext().Get<ApplicationDbContext>();

And:

Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

To:

HttpContext.Current.Request.GetOwinContext().Get<ApplicationDbContext>();
HttpContext.Current.Request.GetOwinContext().GetUserManager<ApplicationUserManager>();

Respectively.

Now, why is that? Is there any difference between using Request and HttpContext.Current.Request to get the Owin Context?

mason
  • 31,774
  • 10
  • 77
  • 121
RottenCheese
  • 869
  • 2
  • 12
  • 18

0 Answers0