0

I have an ASP.NET Core 5 Web API. How can I return the results from all my controllers in a Result object, regardless of the return type of controller?

Something like this:

Result: {
    "isSuccess": {{True or False}},
    "value": {{Result Value Object}},
    "error": {{Error Object}},
    "totalCount": {{number of results, in case the result is list}}
}

1 Answer 1

1

You should be able to implement what you're looking for like this:

public class ResultActionResult<T> : ActionResult
{
    public ResultActionResult(T value)
    {
        Value = value;
        IsSuccess = true;
    }

    public ResultActionResult(Error error)
    {
        Error = error;
        IsSuccess = false;
    }

    public T Value { get; }
    public Error Error { get; }
    public bool IsSuccess { get; }
    public int? TotalCount { get; set; }

    public override async Task ExecuteResultAsync(ActionContext context)
    {
        var objectResult = new ObjectResult(this)
        {
            StatusCode = IsSuccess ? 200 : 400
        };
        await objectResult.ExecuteResultAsync(context);
    }
}

This will give you two constructors: one for successful results and the other one for error results. The four properties: Value will hold the result value object, Error will hold the error object, IsSuccess will be your boolean telling you whether the result is a success or an error, and TotalCount will holds the total number of results in case the result is a list. The class also overrides the ExecuteResultAsync method to return an ObjectResult with a status code of 200 for success and 400 for error.

To use it simply return an instance from your controller action. Hope that's what you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.