Search code examples
c#.net-6.0asp.net-core-3.1

Modify API response before passing back to controller in .NET Core


I'm able to achieve same behavior easily in .NET Framework but coming to .NET Core I don't find needed methods to achieve same

Snippet: below response has only Getter no setter and CreateErrorResponse is not supported

var error = new HttpError
        {
           {
             "data", reqdInfo
           }
        };

context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error);

I want to include above error info in the response before i give back control to controller

Edit: In framework


Solution

  • ASP.NET was heavily reworked since the pre-.NET Core version. Something potentially similar can be achieved with Results class (available since ASP.NET Core 6). For example:

    app.Use(async (context, next) =>
    {
        if (context.Request.Path.Value.Equals("/api/test/error", StringComparison.OrdinalIgnoreCase))
        {
            await Results.Problem(new ProblemDetails
                {
                    Extensions = { { "data", new { Value = 1 } } }
                })
                .ExecuteAsync(context);
        }
        else
        {
            await next();
        }
    });
    

    Which produces the following result for /api/test/error:

    {
        "type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
        "title": "An error occurred while processing your request.",
        "status": 500,
        "data": {
            "value": 1
        }
    }
    

    Potentially useful articles:

    1. Handle errors in ASP.NET Core
    2. Handle errors in ASP.NET Core web APIs
    3. Write custom ASP.NET Core middleware