收到格式错误的请求时,ASPNET Core应用逻辑

时间:2018-08-15 14:50:43

标签: c# asp.net-core middleware

我有一个应用程序,在该应用程序中,我只需要应用格式错误的请求,然后返回响应(状态代码:400)。

为此,我对ASP.NET Core中的错误处理进行了研究,并基于此solution尝试了以下操作:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;

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

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

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        if (context.Response.StatusCode == StatusCodes.Status400BadRequest)
        {
            //apply logic
        }
        var result = JsonConvert.SerializeObject(new { error = exception.Message });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)StatusCodes.Status400BadRequest;
        return context.Response.WriteAsync(result);
    }
}

并在启动中:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));
        app.UseMvc();
    }

不幸的是,上述解决方案无法正常工作,当我调试时,即使请求格式不正确,我也发现context.Response.StatusCode始终为200。

我在这里想念什么?任何见识将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试检查Response Status

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.Use(async (context,next) => {
            await next();
            if (context.Response.StatusCode == StatusCodes.Status400BadRequest)
            {
                    var result = JsonConvert.SerializeObject(new { error = "Not Support" });
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = (int)StatusCodes.Status400BadRequest;
                    await context.Response.WriteAsync(result);
            }
        });