我正在使用 asp.net mvc 5来开发一个Web应用程序。但是我在玩用户帐户时遇到了一些错误。我创建了一个用户帐户,我想删除它,但在使用 ajax-jquery 执行此操作时面临以下问题。我正在尝试使用 ajax 请求删除用户帐户,但它给出了空对象引用的错误,因为 Owin 上下文由于 ajax 调用而未启动。
public class AdmissionsController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AdmissionsController()
{
}
public AdmissionsController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//function to delete user account
public async Task<object> DeleteUser(string id)
{
ApplicationDbContext context = new ApplicationDbContext();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await _userManager.FindByIdAsync(id);
var logins = user.Logins;
var rolesForUser = await _userManager.GetRolesAsync(id);
using (var transaction = context.Database.BeginTransaction())
{
foreach (var login in logins.ToList())
{
await _userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
}
if (rolesForUser.Count() > 0)
{
foreach (var item in rolesForUser.ToList())
{
// item should be the name of the role
var result = await _userManager.RemoveFromRoleAsync(user.Id, item);
}
}
await _userManager.DeleteAsync(user);
transaction.Commit();
}
return new{success=true};
}
}
我的 ajax 调用如下:
var userid = $(this).attr("data-StudentId");
var success = false;
$.ajax({
method: "Get",
url: "/Area/Admissions/DeleteUser",
data: { "id": userid },
success: function (response) {
if (response.Success == true) {
success = true;
}
else if (response.Success == false) {
//window.location.reload();
}
},
error: function (response) {
notificationMSG("fa fa-thumbs-up", "error", "Error", response.message);
}
});
如何解决此问题???我在以下行收到错误:
var user = await _userManager.FindByIdAsync(id);
这只是
一个疯狂的猜测,但在我看来,你没有实例化_userManager
.您有一个相应的属性,用于进行此创建。但是,在有错误的行中,您使用私有字段。尝试使用该属性:
var user = await UserManager.FindByIdAsync(id);
这将调用 getter,从 owin 上下文中获取此管理器。