ASP.Net 5 MVC 6,如何使用共享的Error.cshtml作为默认错误响应
当使用带有剃刀视图的Microsoft.AspNet.Diagnostics UseExceptionHandler中间件时
如果您查看https://github.com/aspnet/Diagnostics/tree/dev/samples/ExceptionHandlerSample/Startup.cs的示例代码
解释如何使用Microsoft.AspNet.Diagnostics ASP.NET 5的ErrorHandler中间件,一个评论说:
//通常你会使用MVC或类似的渲染一个漂亮的页面.
好的,但是怎么做呢?
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中:
public IActionResult Error() { var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>(); return View("~/Views/Shared/Error.cshtml",feature?.Error); }
Error.cshtml视图可能如下所示:
@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) }