ASP.Net 5 MVC 6,如何使用共享的Error.cshtml作为默认错误响应 [英] ASP.Net 5 MVC 6, how to use shared Error.cshtml as default error response
问题描述
ASP.Net 5 MVC 6,如何使用共享的Error.cshtml作为默认错误响应
当使用带有剃刀视图的Microsoft.AspNet.Diagnostics UseExceptionHandler中间件时
如果您在 https://github.com/aspnet上查看示例代码/Diagnostics/tree/dev/samples/ExceptionHandlerSample/Startup.cs 解释如何为ASP.Net 5使用Microsoft.AspNet.Diagnostics ErrorHandler中间件,评论说:
If you look at the sample code at https://github.com/aspnet/Diagnostics/tree/dev/samples/ExceptionHandlerSample/Startup.cs explaning how to use Microsoft.AspNet.Diagnostics ErrorHandler middleware for ASP.Net 5,a comment say:
//通常,您将使用MVC或类似的东西来呈现漂亮的页面.
// Normally you'd use MVC or similar to render a nice page.
好,但是该怎么做?
public class Startup
{
public void Configure(IApplicationBuilder app)
{
// Configure the error handler to show an error page.
app.UseExceptionHandler(errorApp =>
{
// Normally you'd use MVC or similar to render a nice page.
errorApp.Run(async context =>
{
推荐答案
在启动类中:
app.UseExceptionHandler("/Home/Error");
在HomeController中:
in HomeController:
public IActionResult Error()
{
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
return View("~/Views/Shared/Error.cshtml", feature?.Error);
}
Error.cshtml视图如下所示:
the Error.cshtml view can look like :
@model Exception
@{
ViewBag.Title = "Oops!";
}
<h1 class="text-danger">Oops! an error occurs</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model != null)
{
@Html.ValueFor(model => model.Message)
}
此代码是 GitHub
这篇关于ASP.Net 5 MVC 6,如何使用共享的Error.cshtml作为默认错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!