ASP.NET-CORE-MVC / 2个自定义错误页面,每个页面仅负责一个指定的错误

时间:2018-07-17 13:06:55

标签: error-handling asp.net-core-mvc

我在 Startup.cs 中使用app.UseDeveloperExceptionPage();来显示我的网站可能存在的任何自定义例外。现在,我的目标是制作一个仅针对我指定的单个错误的自定义错误页面。

例如,假设我在 HomeController.cs 中写了一些东西,这将故意给我一个例外。我只想为该特定错误创建一个自定义错误页面,并且希望其余的错误像往常一样由app.UseDeveloperExceptionPage();处理。

现在基本上我想针对2个不同页面上的2个特定错误执行此操作,因此我需要制作2个自定义错误页面,每个页面都负责我选择的一个特定错误。

我该如何实现?差不多了,告诉我是否需要提供更多信息。

1 个答案:

答案 0 :(得分:0)

您只能通过使用1个这样的视图来实现 首先,您需要定义以让.Net核心知道如何处理错误

app.UseExceptionHandler("/Error/500");
app.Use(async (context, next) =>
   {
      await next();
      if (context.Response.StatusCode == 404)
      {
         context.Request.Path = "/Error/404";
         await next();
      }
  });

所以基本上我将处理500、404错误并将其重定向到我的错误控制器

然后创建ErrorController

    public class ErrorController: Controller
    {
        private readonly IExceptionHandler _exceptionHandler;
        public ErrorController(IExceptionHandler exceptionHandler)
        {
            _exceptionHandler = exceptionHandler;
        }

        [HttpGet("/Error/{statusCode}")]
        public async Task<IActionResult> Index(int statusCode)
        {
            if (statusCode == (int)HttpStatusCode.InternalServerError)
            {
                var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
                var exceptionThatOccurred = exceptionFeature.Error;
                await _exceptionHandler.HandleExceptionAsync(exceptionThatOccurred);
            }
            return View(statusCode);
        }
    }

然后终于。

@{
    ViewData["Title"] = Model;
}
@model int
@{
    var statusCode = Model;
    var statusmessage = "";
    switch (statusCode)
    {
        case 400:
            statusmessage = "Bad request: The request cannot be fulfilled due to bad syntax";
            break;
        case 403:
            statusmessage = "Forbidden: You are not authorize to use system. Please contact admin for detail";
            break;
        case 404:
            statusmessage = "Page not found";
            break;
        case 408:
            statusmessage = "The server timed out waiting for the request";
            break;
        case 500:
            statusmessage = "Internal Server Error";
            break;
        default:
            statusmessage = "That’s odd... Something we didn't expect happened";
            break;
    }
}

<div class="error-page-wrapper row2">
    <div id="error-container" class="clear">
        <div id="error-page" class="clear">
            <div class="hgroup">
                <h1>@statusmessage</h1>
                <h2>@Model Error</h2>
            </div>
            <p>Go <a href="javascript:history.go(-1)">Back</a> or <a href="/">Home</a></p>
        </div>
    </div>
</div>

因此,您可以看到if子句处理500错误,如果您不想处理500错误,则可以将其删除。

如果您有任何问题,请告诉我