Search code examples
c#asynchronousasp.net-web-apimediatypeformatter

How to format response in an async WebAPI method?


If I have an async web API method, then the Request object is null (as id discussed in other posts such as this one).

It seems that the most common means of returning a response in this circumstance is to use something like

return new HttpResponseMessage(HttpStatusCode.OK) {
   Content = new ObjectContent<T>(myObj, new JsonMediaTypeFormatter())
};

But whatabout the formatting? Normally the Request object handles that because it knows what was requested, but if I don't have a Request object then how do I know the requested format?webapi


Solution

  • All of my web API methods are asynchronous, and I've never had a problem returning data. This is what a typical controller method looks like in one of my projects:

    [HttpGet]
    [Route("v1/samples/{id}", Name="SampleGet")]
    [ResponseType(typeof(string))]
    public async Task<IHttpActionResult> Get(int id)
    {
        return Ok("value");
    }
    

    Like I said, I've never had problems doing it like this and all of my current projects follow this general pattern.

    Unit testing the response looks like this. To test for an OK response using NUnit and FluentAssertions:

    [Test]
    public async Task GetReturns200IfSuccessful()
    {
        //Arrange
    
        //Act
        var response = await _sut.GetAsync();
    
        //Assert
        response.Should().BeOfType<OkNegotiatedContentResult<string>();
    }
    

    If you wanted to check the value of the response, you do this:

    [Test]
    public async Task GetReturnsValue()
    {
        //Act
        var response = await _sut.GetAsync();
        var result = response as OkNegotiatedContentResult<AssetList>;
    
         //Assert
         result.Should().Be("value");
    }
    

    Hope that helps.