Search code examples
asp.net-coreasp.net-core-2.2

How to change api return result in asp.net core 2.2?


My requirement is when the return type of the action is void or Task, I'd like to return my custom ApiResult instead. I tried the middleware mechanism, but the response I observed has null for both ContentLength and ContentType, while what I want is a json representation of an empty instance of ApiResult. Where should I make this conversion then?


Solution

  • There are multiple filter in .net core, and you could try Result filters.

    For void or Task, it will return EmptyResult in OnResultExecutionAsync.

    Try to implement your own ResultFilter like

    public class ResponseFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // do something before the action executes
            if (context.Result is EmptyResult)
            {
                context.Result = new JsonResult(new ApiResult());
            }
            var resultContext = await next();
            // do something after the action executes; resultContext.Result will be set
        }
    }
    public class ApiResult
    {
        public int Code { get; set; }
        public object Result { get; set; }
    }
    

    And register it in Startup.cs

    services.AddScoped<ResponseFilter>();
    services.AddMvc(c =>
                    {                       
                        c.Filters.Add(typeof(ResponseFilter));
                    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);