C# r被接受,因为它对实际发生的事情提供了深入的解释。如果你能把你的评论放在一起作为“答案”,我会把它标记为接受。谢谢 An unhandled exception occurred while processing the request. ObjectD
r被接受,因为它对实际发生的事情提供了深入的解释。如果你能把你的评论放在一起作为“答案”,我会把它标记为接受。谢谢C# r被接受,因为它对实际发生的事情提供了深入的解释。如果你能把你的评论放在一起作为“答案”,我会把它标记为接受。谢谢 An unhandled exception occurred while processing the request. ObjectD,c#,asp.net-core,asp.net-core-mvc,C#,Asp.net Core,Asp.net Core Mvc,r被接受,因为它对实际发生的事情提供了深入的解释。如果你能把你的评论放在一起作为“答案”,我会把它标记为接受。谢谢 An unhandled exception occurred while processing the request. ObjectDisposedException: Cannot access a disposed object. Object name: 'TestDb'. Microsoft.Data.Entity.DbContext.get_ServiceProvi
An unhandled exception occurred while processing the request.
ObjectDisposedException: Cannot access a disposed object.
Object name: 'TestDb'.
Microsoft.Data.Entity.DbContext.get_ServiceProvider()
private readonly UserManager<ApplicationUser> userManager;
// controller's constructor
public AuthController(UserManager<ApplicationUser> userManager) {
this.userManager = userManager;
}
[AllowAnonymous, HttpPost]
public async Task<ActionResult> ForgotPass(ForgotPassViewModel model) {
//model checks
var user = new UserQuery(db).GetUserByUserName(model.UserName);
//check if user exists
var token = await userManager.GeneratePasswordResetTokenAsync(user);
var url = $"{config.Url}/auth/resetpass?user={user.Id}&token={WebUtility.UrlEncode(token)}";
// send email with the reset url
model.Success = "An email has been sent to your email address";
return View(model);
}
[AllowAnonymous, HttpPost]
public async Task<ActionResult> ResetPass(ResetPassViewModel model) {
//model checks
var user = new UserQuery(db).GetUserById(model.UserId);
//error occurs here:
var result = await userManager.ResetPasswordAsync(user, model.Token, model.Password);
//check result
model.Success = "Password successfully reset";
return View(model);
}
public ApplicationUser GetUserByUserName(string userName) {
using (var db = this.dbContext) {
var user = (from u in db.Users
where u.UserName == userName
select u).SingleOrDefault();
return user;
}
}
var user = await userManager.FindByEmailAsync(model.UserName);
var user = await userManager.FindByIdAsync(model.UserId);
DbContext context = null;
try
{
context = new DbContext();
...stuff inside the using block ...
}
finally
{
if(context!=null)
context.Dispose()
}
using(DbContext context = new DbContext())
{
...stuff inside the using block ...
}
services.AddTransient<Func<MyDbContext>>( (provider) => new Func<MyDbContext>( () => new MyDbContext()));
public class MyService
{
public readonly Func<MyDbContext> createMyContext;
public MyService(Func<MyDbContext> contextFactory)
{
this.createContext = contextFactory;
}
public User GetUserById(Guid userId)
{
// note we're calling the delegate here which
// creates a new instance every time
using(var context = createContext())
{
return context.User.FirstOrDefault(u => u.Id = userId);
}
}
}