ASP.NET 5/6 MVC相当于HttpException的 [英] ASP.NET 5 / MVC 6 equivalent of HttpException

查看:370
本文介绍了ASP.NET 5/6 MVC相当于HttpException的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

你可以做的,就是<一href="http://www.mikesdotnetting.com/Article/269/asp-net-5-middleware-or-where-has-my-httpmodule-gone"相对=nofollow>挂钩到通过中间件中的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.

下面是从<一个例子href="https://github.com/aspnet/Diagnostics/blob/dev/src/Microsoft.AspNet.Diagnostics/ExceptionHandler/ExceptionHandlerMiddleware.cs"相对=nofollow>来源$ 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>();
    }
}

这篇关于ASP.NET 5/6 MVC相当于HttpException的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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