c# - 无法删除用户外部登录

标签 c# asp.net-identity-2 asp.net-mvc-5.2

我正在尝试使用个人帐户的 MVC 5.2 模板。一切正常,除了当我尝试删除用户登录时收到以下错误消息:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

在 ManagerController 的下面一行:

var result = await this.UserManager.RemoveLoginAsync(this.User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));

这是完整的 RemoveLogin 操作:

    [HttpPost]
    [Route("RemoveLogin")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
    {
        ManageMessageId? message;
        var result = await this.UserManager.RemoveLoginAsync(this.User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
        if( result.Succeeded )
        {
            var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
            if( user != null )
                await this.SignInAsync(user, isPersistent: false);
            message = ManageMessageId.RemoveLoginSuccess;
        }
        else
            message = ManageMessageId.Error;

        return this.RedirectToAction("ManageLogins", new { Message = message });
    }

最佳答案

我能够通过更改行来让它工作:

public async Task<IActionResult> RemoveLogin(
    string loginProvider, 
    string providerKey)

public async Task<IActionResult> RemoveLogin(
    [Bind(Prefix = "Account.LoginProvider")]string loginProvider,
    [Bind(Prefix = "Account.ProviderKey")]string providerKey)

原因:

无论出于何种原因,MVC 绑定(bind)都没有正确解析参数绑定(bind):

<input asp-for="@account.LoginProvider" type="hidden" />
<input asp-for="@account.ProviderKey" type="hidden" />

正在创建以下表单:

<input type="hidden" id="account_LoginProvider" name="account.LoginProvider" value="Facebook">
<input type="hidden" id="account_ProviderKey" name="account.ProviderKey" value="...">

这些名称未绑定(bind)到参数名称 loginProvider 和 providerKey。

这是提供解决方法的答案:

https://stackoverflow.com/a/3869512/567524

关于c# - 无法删除用户外部登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158289/

相关文章:

c# - Autofac:如何注册具有多个类型参数的泛型?将 IGenRepo<T, TKey> 注册到 EFGenRepo<T, TKey>

c# - 传递接口(interface)而不是对象实例

c# - 为 SVN 修改提交时的文本文件,让我的程序知道它的提交号

c# - 使用 MySQL 和 Entity Framework 的 ASP.NET 标识

c# - ASP.NET MVC 5.1 C# OWIN facebook 身份验证或登录要求生日、喜欢、公共(public)资料、电话号码

c# - Routes.AppendTrailingSlash 排除部分路线

c# - 使用 EF Core 删除范围

c# - 在Screen Coordinates中获取桌面上任意窗口的边界,可以吗?

asp.net-mvc - ASP.Net MVC 5 w/identity 2.2.0 注销不起作用

authentication - 在Web Api 2中授予刷新 token 时更新角色