question

$$ANON_USER$$ avatar image
0 Votes"
$$ANON_USER$$ asked ZhiLv-MSFT commented

Cannot access a disposed object 'ApplicationUserManager'

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]: /answers/storage/attachments/200335-image.png

dotnet-aspnet-core-generaldotnet-aspnet-core-mvcdotnet-aspnet-mvc
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The code is a bit of a head scratcher. the screenshot is not the same as the posted code. The two using objects are never referenced. There's a new DbContext that is also unused. It looks like you are trying to find a user but the GrantResourceOwnerCredentials does nothing.

What is the intent of your code?

Anyway, the reason for the error is the userManager and Task.Run have different scopes and context that can exist at any time.



0 Votes 0 ·

Hi anonymous user,
I noticed that you have edited the code, is the issue resolved, or are there any updates on the issue?

0 Votes 0 ·

Hi @ZhiLv-MSFT

yes issue fixed as per change my code as per mention above..

0 Votes 0 ·

Glad to hear that. I have converted my previous comment as an answer, hope it can help others who meet the similar issue.

0 Votes 0 ·

1 Answer

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

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);
             }
         }); 
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.