When to return IHttpActionResult vs Object

后端 未结 2 1534
故里飘歌
故里飘歌 2020-12-28 14:29

In examples of using the ASP.NET Web API I see two different methods used to return data to the calling jQuery function. The first method returns an object of type Cli

相关标签:
2条回答
  • 2020-12-28 15:02

    The second method allows you to return just status codes (like the 404 in the example), streaming file content and other types of non-object content.

    0 讨论(0)
  • 2020-12-28 15:03

    Returning IHttpActionResult provides a nice separation of concerns.

    Your controller can focus on responding to the request in the most sensible manner (status codes, error messages, etc.). Another (service) layer can focus on actually retrieving and transforming the business data.

    The side-effect is, your controller methods become more unit testable. Consider the following simple example:

    public class MyController : ApiController
    {
        //or better yet, dependency-inject this
        SomeService _service = new SomeService();
    
        public IHttpActionResult Get(int id)
        {
             if (id < 0)
                 return BadRequest("Some error message");
    
             var data = _service.GetData(id);
    
             if (data == null)
                return NotFound();
    
             return Ok(data);
        }
    }
    

    Not only is this method's logic understandable just by reading it, but you could now test the logic more easily and naturally, something like (using NUnit syntax):

    [TestFixture]
    public class MyControllerTests
    {    
        [Test]
        public void Get_WithIdLessThan0_ReturnsBadRequest()
        {
            var controller = new MyController();
            int id = -1;
    
            IHttpActionResult actionResult = controller.Get(id);
    
            Assert.IsInstanceOf<BadRequestErrorMessageResult>(actionResult);
        }
    }
    

    Similarly, you could mock the Service layer and test what happens when you give known id parameters to the controller, etc.

    Here is a good article on Unit Testing Controllers in Web Api

    0 讨论(0)
提交回复
热议问题