According to [1], some advantages of using the IHttpActionResult interface are:

  1. Simplifies unit testing your controllers.
  2. Moves common logic for creating HTTP responses into separate classes.
  3. Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.

Today, we are going to customize IHttpActionResult to create a class VersionedTextResult to support API versioning based on TextResult in [1].

public class VersionedTextResult : IHttpActionResult
{
    string _value;
    string _version;
    HttpRequestMessage _request;

    public TextResult(string value, string version, 
			HttpRequestMessage request)
    {
        _value = value;
        _version = version;
        _request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(
        CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage()
        {
            Content = new StringContent(_value),
            RequestMessage = _request
        };
        var responseHeadersContentType = 
            response.Content.Headers.ContentType; 
        NameValueHeaderValue versionParamter = 
            new NameValueHeaderValue("version", Version);
        responseHeadersContentType.Parameters.Add(versionParamter);
        return Task.FromResult(response);
    }
}

 

References:

  1. https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results
  2. https://docs.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api
Advertisements