ASP.NET 5/6 MVC相当于HttpException的NET、ASP、HttpException、MVC

由网友(带你飞@)分享简介:在MVC 5,你可以抛出一个HttpException与HTTP code,这将设置像这样的反应:In MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so:throw new H...

在MVC 5,你可以抛出一个HttpException与HTTP code,这将设置像这样的反应:

In MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so:

throw new HttpException((int)HttpStatusCode.BadRequest, "Bad Request.");

HttpException不会在ASP.NET 5 / MVC 6.存在什么是相当于code?

HttpException does not exist in ASP.NET 5 / MVC 6. What is the equivalent code?

推荐答案

一个短暂的聊天@davidfowl < /一>,似乎ASP.NET 5具有 HttpException 的Htt presponseException 没有这样的概念, 神奇转向响应消息。

After a brief chat with @davidfowl, it seems that ASP.NET 5 has no such notion of HttpException or HttpResponseException that "magically" turn to response messages.

你可以做的,就是挂钩到通过中间件中的ASP.NET 5管道,并建立一个处理异常你。

What you can do, is hook into the ASP.NET 5 pipeline via MiddleWare, and create one that handles the exceptions for you.

下面是从来源$ C ​​$ C自己的错误处理中间件将设置响应状态code 500在异常的进一步上涨管道:

Here is an example from the source code of their error handler middleware which will set the response status code to 500 in case of an exception further up the pipeline:

public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ErrorHandlerOptions _options;
    private readonly ILogger _logger;

    public ErrorHandlerMiddleware(RequestDelegate next, 
                                  ILoggerFactory loggerFactory,
                                  ErrorHandlerOptions options)
    {
        _next = next;
        _options = options;
        _logger = loggerFactory.CreateLogger<ErrorHandlerMiddleware>();
        if (_options.ErrorHandler == null)
        {
            _options.ErrorHandler = _next;
        }
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError("An unhandled exception has occurred: " + ex.Message, ex);

            if (context.Response.HasStarted)
            {
                _logger.LogWarning("The response has already started, 
                                    the error handler will not be executed.");
                throw;
            }

            PathString originalPath = context.Request.Path;
            if (_options.ErrorHandlingPath.HasValue)
            {
                context.Request.Path = _options.ErrorHandlingPath;
            }
            try
            {
                var errorHandlerFeature = new ErrorHandlerFeature()
                {
                    Error = ex,
                };
                context.SetFeature<IErrorHandlerFeature>(errorHandlerFeature);
                context.Response.StatusCode = 500;
                context.Response.Headers.Clear();

                await _options.ErrorHandler(context);
                return;
            }
            catch (Exception ex2)
            {
                _logger.LogError("An exception was thrown attempting
                                  to execute the error handler.", ex2);
            }
            finally
            {
                context.Request.Path = originalPath;
            }

            throw; // Re-throw the original if we couldn't handle it
        }
    }
}

和你需要用它注册 StartUp.cs

public class Startup
{
    public void Configure(IApplicationBuilder app, 
                          IHostingEnvironment env, 
                          ILoggerFactory loggerfactory)
    {
       app.UseMiddleWare<ExceptionHandlerMiddleware>();
    }
}
阅读全文

相关推荐

最新文章