简体   繁体   中英

Custom API response HTTP status codes with ABP Framework

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

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.

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!
    }

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>());

You can also use UserFriendlyException we allows you to pass response code. Example: throw new UserFriendlyException (302, "Redirecting...");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM