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

如何自定义OpenIddict客户端错误显示为标准MVC视图?

自定义OpenIddict客户端错误显示为MVC视图

要将OpenIddict客户端返回的纯文本错误改为标准MVC视图展示,可通过以下两种方式实现:

方法一:修改回调控制器逻辑

  1. 更新回调动作方法
    在AccountController的Callback方法中,捕获认证失败的错误信息,并重定向到现有错误页面:

    public async Task<IActionResult> Callback()
    {
        var result = await HttpContext.AuthenticateAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme);
    
        if (!result.Succeeded)
        {
            // 从认证失败结果中提取错误参数
            var error = result.Failure?.Properties?.GetString("error");
            var errorDescription = result.Failure?.Properties?.GetString("error_description");
            var errorUri = result.Failure?.Properties?.GetString("error_uri");
    
            // 重定向到Error控制器,传递错误参数
            return RedirectToAction("Index", "Error", new 
            { 
                error, 
                errorDescription, 
                errorUri 
            });
        }
    
        // 认证成功后的原有逻辑...
        return RedirectToAction("Index", "Home");
    }
    
  2. 扩展Error视图模型
    在ErrorViewModel中添加错误相关属性:

    public class ErrorViewModel
    {
        public string RequestId { get; set; }
        public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
        
        // 新增错误属性
        public string Error { get; set; }
        public string ErrorDescription { get; set; }
        public string ErrorUri { get; set; }
    }
    
  3. 更新Error视图
    修改Views/Error/Index.cshtml,添加错误信息的展示逻辑:

    @model ErrorViewModel
    
    @{
        ViewData["Title"] = "Error";
    }
    
    <h1 class="text-danger">Request Processing Failed</h1>
    
    @if (!string.IsNullOrEmpty(Model.Error))
    {
        <div class="alert alert-danger mt-3">
            <strong>Error Code:</strong> @Model.Error
        </div>
    }
    
    @if (!string.IsNullOrEmpty(Model.ErrorDescription))
    {
        <div class="alert alert-danger">
            <strong>Details:</strong> @Model.ErrorDescription
        </div>
    }
    
    @if (!string.IsNullOrEmpty(Model.ErrorUri))
    {
        <div class="alert alert-info">
            <strong>Learn More:</strong> <a href="@Model.ErrorUri" target="_blank">@Model.ErrorUri</a>
        </div>
    }
    
    @if (Model.ShowRequestId)
    {
        <p class="mt-3">
            <strong>Request ID:</strong> <code>@Model.RequestId</code>
        </p>
    }
    

方法二:全局拦截OpenIddict认证失败事件

如果不想修改控制器,可通过配置OpenIddict客户端事件,直接替换默认的纯文本错误响应:

builder.Services.AddOpenIddict()
    .AddClient(options =>
    {
        // 保留原有客户端配置(如授权端点、客户端ID等)...

        // 拦截认证失败事件,重定向到错误页面
        options.AddEventHandler<OpenIddictClientEvents.AuthenticationFailedContext>(builder =>
            builder.UseInlineHandler(context =>
            {
                // 构造错误参数的URL编码字符串
                var errorParams = new Dictionary<string, string>
                {
                    ["error"] = context.Error,
                    ["error_description"] = context.ErrorDescription,
                    ["error_uri"] = context.ErrorUri
                };
                var queryString = QueryString.Create(errorParams);

                // 重定向到错误页面
                context.Response.Redirect($"/Error{queryString}");
                return Task.CompletedTask;
            }));
    });

完成以上配置后,当访问https://localhost:44338/callback/login/local触发missing_token错误时,会自动跳转到格式化的MVC错误页面,而非纯文本响应。

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:35:32