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中间件,评论说:
//通常你会使用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 =>
{
答案 0 :(得分:26)
:
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)
}
此代码是GitHub
上提供的项目的一部分答案 1 :(得分:7)
要处理404s和内部错误,您需要修改错误签名。
我已经在Startup.cs中的Dev环境中明确地注释掉了调试错误处理程序。如果您不想这样做,请使用项目中的环境变量。
将其添加到Startup.cs
if (env.IsDevelopment())
{
// Uncomment when done testing error handling
//app.UseBrowserLink();
//app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
// Comment when done testing error handling
app.UseExceptionHandler("/Home/Error");
}
else
{
app.UseExceptionHandler("/Home/Error");
//For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}
// Lines Skipped For Brevity ....
// Add this line above app.Mvc in Startup.cs to Handle 404s etc
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
将其添加到HomeController.cs
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Http.Features;
// id = Http Status Error
public IActionResult Error(String id)
{
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var undhandledException = feature?.Error;
var iisError = id;
return View();
}
答案 2 :(得分:0)
我正在使用Visual Studio 2019和MVC 5:
以下是Controller类中的内容:
public ActionResult Save(MyObject obj)
{
try
{
//Write cde here that could break..maybe an update or new object etc
//...
///successful
}
catch (Exception e)
{
return View("Error", new HandleErrorInfo(e, "Home", "Error"));
}
return RedirectToAction("Index", "Home"); //redir to list
}
这将转到Views \ Shared \文件夹中的Error.cshtml。 这对我有用。