Advantage of using IActionResult as result type in Actions

你说的曾经没有我的故事 提交于 2020-01-10 17:30:04

问题


What's the advantage or recommendation on using IActionResult as the return type of a WebApi controller instead of the actual type you want to return?

Most of the examples I've seen return IActionResult, but when I build my first site I exclusively use View Model classes as my return types.... now I feel like I did it all wrong!


回答1:


The main advantage is that you can return error/status codes or redirects/resource urls.

For example:

public IActionResult Get(integer id) 
{
    var user = db.Users.Where(u => u.UserId = id).FirstOrDefault();

    if(user == null) 
    {
        // Returns HttpCode 404
        return NotFound();
    }

    // returns HttpCode 200
    return ObjectOk(user);
}

or

public IActionResult Create(User user) 
{
    if(!ModelState.IsValid) 
    {
        // returns HttpCode 400
        return BadRequest(ModelState);
    }

    db.Users.Add(user);
    db.SaveChanges();

    // returns HttpCode 201
    return CreatedAtActionResult("User", "Get", new { id = user.Id} );
}



回答2:


The main advantage is that you can easily test your code using a mocking framework.

And as you build your controllers, you can easily change your return object as well. IActionResult is a interface and has many implementations like JsonResult, ViewResult, FileResult and so on.



来源:https://stackoverflow.com/questions/37998291/advantage-of-using-iactionresult-as-result-type-in-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!