Cannot access a disposed object 'ApplicationUserManager'

Anonymous
2022-05-09T14:44:58.873+00:00

Startup.cs public class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } // normal public Startup() : this(false) { } // testing public Startup(bool isDev) { // add settings Settings.Configure(isDev); OAuthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/Token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new AuthorizationServerProvider() }; } public void Configuration(IAppBuilder app) { // Configure the db context, user manager and role manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); app.CreatePerOwinContext<LoanManager>(BaseManager.Create); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); // token generation app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AuthenticationType = "Bearer", AuthenticationMode = AuthenticationMode.Active }); } } AuthorizationServerProvider.cs public class AuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "" }); var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); IdentityUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); } } WebApiConfig.cs public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); // enable CORS for all hosts, headers and methods var cors = new EnableCorsAttribute("", "", ""); config.EnableCors(cors); config.Routes.MapHttpRoute( name: "optional params", routeTemplate: "api/{controller}" ); config.Routes.MapHttpRoute( name: "Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // stop cookie auth config.SuppressDefaultHostAuthentication(); // add token bearer auth config.Filters.Add(new MyAuthenticationFilter()); //config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType)); config.Filters.Add(new ValidateModelAttribute()); if (Settings.IsDev == false) { config.Filters.Add(new AuthorizeAttribute()); } // make properties on model camelCased var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); } MyAuthenticationFilter.cs public class MyAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter { public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (context.Principal != null && context.Principal.Identity.IsAuthenticated) { } return Task.FromResult(0); } public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } } ![200335-image.png][1] [1]: /api/attachments/200335-image.png?platform=QnA

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,360 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,404 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,076 Reputation points Microsoft Vendor
    2022-05-10T02:37:23.697+00:00

    Agree with AgaveJoe, your code is not very clear. Please explain more detail about the code. Besides, from your code, it seems that there is no need to add the userManager.FindAsync method in the using statement, try to change the code order as below:

            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
            var applicationUser1 = await userManager.FindAsync(username, password);
    
            await Task.Run(async () =>
            {
                try
                {
                    using (ApplicationDbContext applicationDbContext = new ApplicationDbContext())
                    {
                        using (ApplicationUserStore applicationUserStore = new ApplicationUserStore(applicationDbContext))
                        {
                            DBContext dBContext = new DBContext();
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                }
            }); 
    
    0 comments No comments

0 additional answers

Sort by: Most helpful