我有一个基本路由的非常基本的asp.net MVC 6应用程序,我有一个自定义的ErrorController来将错误路由到某些视图。
但我希望当用户键入不存在的URL时,会抛出异常(我可以处理它)。但是,当我输入一些随机URL时,不会抛出任何异常,我只是得到一个空白页面。我非常确定这在MVC< MVC< 6。
如果我只是在控制器中抛出异常,错误处理本身就可以正常工作。
Startup.cs(部分)
public void Configure(IApplicationEnvironment appEnv, IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(HandleException);
}
app.UseStaticFiles();
app.UseMvc(routes => MapRoutes(routes, appEnv));
}
private static void MapRoutes(IRouteBuilder routes, IApplicationEnvironment env)
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "main", action = "index" });
}
private static void HandleException(IApplicationBuilder errorApp)
{
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
errorApp.Run(async context => HandleErrorContext(context));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
}
private static void HandleErrorContext(HttpContext context)
{
var error = context.Features.Get<IExceptionHandlerFeature>();
var exception = error.Error;
if (exception == null)
{
context.Response.Redirect("../error/external");
}
else if (exception is ExpirationException)
{
context.Response.Redirect("../error/expired");
}
else if (exception is HttpException)
{
var httpException = exception as HttpException;
int code = httpException.GetHttpCode();
context.Response.Redirect("../error/external?code=" + code);
}
else
{
context.Response.Redirect("../error/external");
}
}
答案 0 :(得分:1)
不能直接回答我的问题,但我已经从https://stackoverflow.com/a/4833519/2713516开始工作了。我仍然想知道为什么asp.net不会抛出404.
routes.MapRoute(
"PageNotFound",
"{*catchall}",
new { controller = "Home", action = "PageNotFound" }
);
答案 1 :(得分:1)
您可以通过将 StatusCodePages 中间件添加到管道来显示用户友好的错误页面。 In Startup.cs
public void Configure(IApplicationEnvironment appEnv, IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error/500");
app.UseStatusCodePagesWithReExecute("/error/{0}");
}
app.UseStaticFiles();
app.UseMvc(routes => MapRoutes(routes, appEnv));
}
应该通过重新执行路径/error/{0}
生成响应正文。
[Route("[controller]")]
public class ErrorController : Controller
{
[HttpGet("{statusCode}")]
public IActionResult Error(int statusCode)
{
//switch (statusCode)
//{
// return different views...
//}
Response.StatusCode = statusCode;
return View("Error", statusCode);
}
}
如何显示404错误页面或任何其他错误页面。