使用 ABP 框架自定义 API 响应 HTTP 状态代码 [英] Custom API response HTTP status codes with ABP Framework

查看:51
本文介绍了使用 ABP 框架自定义 API 响应 HTTP 状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用 ASP.NET Boilerplate 返回自定义 HTTP 状态代码(如 4xx)?

Is there any way to return custom HTTP Status Codes (like 4xx) with ASP.NET Boilerplate?

我想在验证上下文中设置自定义应用程序特定的 HTTP 代码以添加更多粒度.目前,ABP 会为所有验证错误设置 200(OK).

I would like to set custom application specific HTTP codes in context of validation to add more granularity. Currently ABP would set 200(OK) for all validation errors.

在 ABP 源代码中,可以看到如下几个地方,其中 Response.StatusCode 由框架设置,如下所示:

In ABP source code is see few places like one below where Response.StatusCode is set by the framework like here :

    private void HandleAndWrapException(ExceptionContext context)
    {
        if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
        {
            return;
        }

        context.HttpContext.Response.Clear();
        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        context.Result = new ObjectResult(
            new AjaxResponse(
                _errorInfoBuilder.BuildForException(context.Exception),
                context.Exception is AbpAuthorizationException
            )
        );

        context.Exception = null; //Handled!
    }

推荐答案

我最终做的是完全替换 ABP 异常过滤器.在我的自定义过滤器中,我可以设置我需要的任何状态代码.

What I eventually did was replace ABP exception filter altogether. In my custom filter I could set any status code I need.

var filters = Configuration.Modules.AbpWebApi().HttpConfiguration.Filters;
var currentExceptionFilter = filters
    .First(h => h.Instance is AbpExceptionFilterAttribute).Instance;

filters.Remove(currentExceptionFilter );
filters.Add(IocManager.Resolve<MyApiExceptionFilter>());

这篇关于使用 ABP 框架自定义 API 响应 HTTP 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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