StatusCodeResult or ResponseMessageResult

12,723

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");
}
Share:
12,723
Craig W.
Author by

Craig W.

I've been working in the information technology field full-time since 1986. I cut my teeth in the VAX/VMS world, moved into Windows development with PowerBuilder and made the switch to the Microsoft stack in 2000. The first .NET application I wrote used Notepad and csc because Visual Studio.NET wasn't out yet. I've been developing in .NET ever since. I'm currently employed as a Sr. Software Engineer/Application Architect/Tech Lead. In addition to crafting software I also really enjoy mentoring and teaching other developers to (hopefully) make them better at their jobs and get them thinking beyond the problem that is right in front of them. Having said that, I do expect the other party to put some effort into solving the problem themselves first (i.e. the old "teach a man to fish" vs. "give a man a fish").

Updated on July 27, 2022

Comments

  • Craig W.
    Craig W. almost 2 years

    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.

  • Craig W.
    Craig W. almost 9 years
    I can do the same thing with the ResponseMessageResult. If I have a variable result that is of type ResponseMessageResult I can reference result.Response.StatusCode.
  • Kiran
    Kiran almost 9 years
    @CraigW: I updated the post with an example. For this simple scenario what you mention equally works but you can look at the above examples and notice that its less code to write too.
  • Craig W.
    Craig W. almost 9 years
    I absolutely agree it's less code to write (my original post basically had what you wrote in your expanded example). Other than that though I still don't see a functional difference between using one of the types over the other.