Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StatusCodeResult or ResponseMessageResult

I've seen a response being sent two different ways from Web API.

return ResponseMessage(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));

or

return StatusCode(HttpStatusCode.UnsupportedMediaType);

Both end up sending a 415 back to the caller. I've looked at the MSDN documentation for the two result classes but still can't figure out what the difference is or why I would choose one over the other.

like image 245
Craig W. Avatar asked Jul 02 '15 17:07

Craig W.


1 Answers

Use StatusCodeResult for easy unit testability.

Example(in xUnit):

var result = Assert.IsType<StatusCodeResult>(valuesController.Blah(data));
Assert.Equal(415, result.StatusCode);

Responding to comment: I would prefer something like below:

public IHttpActionResult Get(int id)
{
    if(id == 10)
    {
        return StatusCode(HttpStatusCode.NotFound);
    }

    return Ok("Some value");
}

rather than:

public IHttpActionResult Get(int id)
{
    if(id == 10)
    {
        return ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound));
    }

    return Ok("Some value");
}
like image 63
Kiran Avatar answered Sep 22 '22 04:09

Kiran