我使用app.UseDeveloperExceptionPage(); in Startup.cs显示我的网站可能具有的任何自定义异常。现在,我的目标是创建一个只针对我指定的单个错误的自定义错误页面。
例如,假设我在HomeController.cs中写了一些东西,它会故意给我一个例外。我只想为这个特定的错误创建一个自定义错误页面,我希望app.UseDeveloperExceptionPage();像往常一样处理其余的错误。
现在,基本上我想对两个不同页面上的两个特定错误进行处理,所以我需要创建两个自定义错误页,每个页面都要对我选择的一个特定错误负责。
我怎样才能做到这一点?差不多了,告诉我是否需要提供更多的信息。
发布于 2018-07-19 03:54:32
只需使用这样的一个视图就可以实现,首先需要进行定义,让.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个错误,可以删除它。
如果你有什么问题请告诉我
https://stackoverflow.com/questions/51382196
复制相似问题