在异常处理程序中看不到自定义响应

时间:2019-03-25 15:16:38

标签: asp.net asp.net-core asp.net-core-webapi

我在asp.net core 2.1应用程序中有一个自定义异常处理程序

img_inv = 255 - img;

我已经在startup.cs中注册了该中间件

    public  class ExceptionHandler
        {

            private readonly RequestDelegate next;

            public ExceptionHandler(RequestDelegate next)
            {
                this.next = next;
            }

            public async Task Invoke(HttpContext context)
            {
                try
                {
                    await next(context);
                }
                catch (Exception ex)
                {
                    await HandleExceptionAsync(context, ex);
                }
            }

            private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
            {
                var result = JsonConvert.SerializeObject(new HttpClientResponseContract
                            {
                                ErrorMessage = exception.Message,
                                ResponseCode = HttpStatusCode.InternalServerError
                            });
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;


                await context.Response.WriteAsync(result);
            }
}

如果发生异常,我可以在此类中命中断点,但在响应中未得到结果对象。实际上,除了响应中的500 Internal Server Error外,我什么也没得到。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

这是正在运行的演示。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseMiddleware<ExceptionHandler>();

    //rest service

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
        routes.MapRoute(
            name: "catalog",
            template: "Catalog/{controller}/{action=Index}/{id?}");

    });
}