How to fix Can't find Request.GetOwinContext in Web API

By FoxLearn 2/18/2024 1:33:47 AM   276
If you get an error can't get the UserManager from OwinContext in ApiController using ASP.NET MVC

You can fix the problem as below.

using System.Web;
using System.Web.Http;
using Microsoft.AspNet.Identity.Owin;
using System.Linq;
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;

namespace Invoice.Controllers
{
    public class AccountController : ApiController
    {
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;

        public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }

        public ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }

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

You should install Microsoft.AspNet.Identity.Owin from the Nuget Package Manager into your project, then just add the following code to the top.

using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;

Remember replace HttpContext.GetOwinContext().Get<ApplicationSignInManager>() to HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>()