基于HTTP状态code ASP.NET MVC 6错误处理 [英] ASP.NET MVC 6 handling errors based on HTTP status code

查看:374
本文介绍了基于HTTP状态code ASP.NET MVC 6错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要显示每个状态code,例如不同的错误消息:

I want to display different error messages for each status code e.g:

  • 400错误的请求
  • 403禁止
  • 500内部服务器错误
  • 404未找​​到
  • 401未授权

我怎样才能在新的ASP.NET MVC应用程序6做到这一点?我可以做到这一点使用内置的UseErrorHandler方法?

How can I achieve this in the new ASP.NET MVC 6 applications? Can I do this using the built in UseErrorHandler method?

application.UseErrorHandler("/error");

另外,我注意到,即使上面的处理,进入了一个不存在的URL,例如/这个页面,不 - 不存在,导致从IIS中一个丑陋的404 Not Found错误页面。这怎么还来处理?

Also, I noticed that even with the above handler, entering a non-existent URL e.g. /this-page-does-not-exist, causes an ugly 404 Not Found error page from IIS. How can this also be handled?

在MVC 5,我们不得不使用ASP.NET的的System.Web程序的customErrors节和在web.config文件中system.webServer httpErrors部分,但它是很难与一个笨拙的工作,有很多很奇怪的行为。难道MVC 6使这个简单了很多?

In MVC 5 we have had to use the system.web customerrors section for ASP.NET and the system.webServer httpErrors section in the web.config file but it was difficult to work with an unwieldy, with lots of very strange behaviour. Does MVC 6 make this a lot simpler?

推荐答案

您可以使用状态codePagesMiddleware 这一点。下面是一个例子:

You could use the StatusCodePagesMiddleware for this. Following is an example:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    app.UseStatusCodePagesWithReExecute("/StatusCodes/StatusCode{0}");

    app.UseMvcWithDefaultRoute();

控制器,它处理的状态code请求:

Controller which handles the status code requests:

public class StatusCodesController : Controller
{
    public IActionResult StatusCode404()
    {
        return View(viewName: "NotFound"); // you have a view called NotFound.cshtml
    }

    ... more actions here to handle other status codes
}

一些注意事项:

Some Notes:

  • 检查如 UseStatus codePagesWithRedirects 其他扩展方法 和 UseStatus codePages 其他功能。
  • 在我试过有状态code。用在我的例子查询字符串,但看起来是这样的 中间件不处理查询字符串,但你可以看看 <一href="https://github.com/aspnet/Diagnostics/blob/3fa5dee2d7f377d57e75fbb0d328cd26b6ff093a/src/Microsoft.AspNet.Diagnostics/Status$c$cPagesExtensions.cs#L121"相对=nofollow>这个 code和解决这个问题。
  • Check other extension methods like UseStatusCodePagesWithRedirects and UseStatusCodePages for other capabilities.
  • I tried having StatusCode as a query string in my example, but looks like this middleware doesn't handle query strings, but you can take a look at this code and fix this issue.

这篇关于基于HTTP状态code ASP.NET MVC 6错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆