You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google登录报错:处理请求时发生未处理异常,未进入ExternalResponse

Google登录未处理异常排查与修复

核心问题分析

你的代码存在两个直接引发崩溃的致命问题:

  1. 重复定义方法:同一个类里重复实现了签名完全一致的GoogleLogin和ExternalResponse方法,会触发编译或运行时冲突,这是崩溃的首要原因。
  2. 使用非ASP.NET Core原生编码工具:调用System.Web.HttpUtility.UrlEncode,但该命名空间并非ASP.NET Core默认依赖,强行使用会引发类型找不到的异常。

修复后的代码示例

先删除一套重复代码,再修正编码逻辑和回调地址传递:

using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;

public IActionResult GoogleLogin(string returnUrl)
{
    // 改用ASP.NET Core原生URL编码方式
    var encodedReturnUrl = Uri.EscapeDataString(returnUrl ?? string.Empty);
    // 生成携带returnUrl的完整回调地址
    var redirectUrl = Url.Action("ExternalResponse", "Home", new { ReturnUrl = encodedReturnUrl });
    var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
    return Challenge(properties, "Google");
}

//CreateBy Burak
public async Task<IActionResult> ExternalResponse(string returnUrl = null, string remoteError = null)
{
    if (!string.IsNullOrEmpty(remoteError))
    {
        return RedirectToAction("Login");
    }

    var authenticateResult = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
    if (authenticateResult?.Succeeded != true)
    {
        return RedirectToAction("Login");
    }

    var user = authenticateResult.Principal;
    var userName = user.Identity.Name;
    var userEmail = user.FindFirst(ClaimTypes.Email)?.Value;
    var userDisplayName = user.FindFirst(ClaimTypes.Name)?.Value;
 
    var contactPersonAccount = new ContactPersonAccount
    {
        UserName = userName,
        NameSurname = userDisplayName,
        //Email = userEmail,
    };

    return RedirectToLocal(returnUrl);
}

额外排查建议

  • 核对Google OAuth配置:确保appsettings.json中的ClientId、ClientSecret与Google开发者控制台一致,回调地址完全匹配。
  • 查看详细异常信息:在开发环境开启appsettings.Development.json中的"DetailedErrors": true,或查看日志文件,获取异常堆栈定位更细节的问题。

内容的提问来源于stack exchange,提问作者MUHAMMET BURAK ÇEVİK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:40:35