IdentityServer4入门五:错误处理

在访问ClientMvc的保护页面时,会跳转到IdentityMvc页面,这时会出现类似下图的错误界面,让人无从入手。

如果你尝试按文字所说的内容去处理。你发现项目已正确设置。其实上面的内容是固定的,其访问的是HomeController的Error方法,该视图是固定了上面的内容。为了能显示有意义的信息我们需要调整视图和控制器。

修改视图

打开View/Shared/Error.cshtml,使用以下内容替换

@model IdentityServer4.Models.ErrorMessage

@{
    var error = Model?.Error;
    var errorDescription = Model?.ErrorDescription;
    var request_id = Model?.RequestId;
}

<div class="error-page">
    <div class="page-header">
        <h1>Error</h1>
    </div>

    <div class="row">
        <div class="col-sm-6">
            <div class="alert alert-danger">
                Sorry, there was an error

                @if (error != null)
                {
                    <strong>
                        <em>
                            : @error
                        </em>
                    </strong>

                    if (errorDescription != null)
                    {
                        <div>@errorDescription</div>
                    }
                }
            </div>

            @if (request_id != null)
            {
                <div class="request-id">Request Id: @request_id</div>
            }
        </div>
    </div>
</div>

  修改HomeController.cs的Error方法

/// <summary>
/// Shows the error page
/// </summary>
public async Task<IActionResult> Error(string errorId)
{            
    // retrieve error details from identityserver
    var message = await _interaction.GetErrorContextAsync(errorId);
    if (message != null)
    {               
        if (!_environment.IsDevelopment())
        {
            // only show in development
            message.ErrorDescription = null;
        }
    }

    return View("Error", message);
}

  Error方法需要额外的两个对象_interaction和_environment,强大的DI(依赖注入)可以帮我们搞定。我们只需要调整HomeController的构造函数,以此来告诉DI我们的控制器所需要的东西。以下是类的前面部分,包括增加的成员和构造函数。

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using IdentityServer4.Services;
using Microsoft.Extensions.Hosting;

namespace IdentityMvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly IIdentityServerInteractionService _interaction;
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<HomeController> _logger;

        public HomeController(IWebHostEnvironment env,
            IIdentityServerInteractionService interaction,
            ILogger<HomeController> logger)
        {
            _environment = env;
            _interaction = interaction;
            _logger = logger;
        }
//....其他代码

  至此,跑一下程序,错误信息不再模糊。

原文地址:https://www.cnblogs.com/kevin-Y/p/11692948.html