Owin Context返回null

时间:2018-01-18 00:59:43

标签: asp.net asp.net-web-api owin-middleware

这是我的DbContext类:

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

这是我的UserManager类:

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

这是我的Startup课程:

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

我有一个WebApiBaseController,其中包含管理器和上下文。 所有其他控制器都从那里继承。

我的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; }
        }
    }

这是我的账户管理员:

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

现在,每当我向该动作发出请求时,我都会收到此回复:

{
    "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个小时。任何一只手? 提前谢谢。

- 编辑: -

好的,我找到了解决方案。 我换了:

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

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

要:

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

分别

现在,为什么?使用RequestHttpContext.Current.Request获取Owin上下文之间有什么区别吗?

0 个答案:

没有答案