Advantage of using IActionResult as result type in Actions

前端 未结 2 982
面向向阳花
面向向阳花 2021-01-01 11:31

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?

2条回答
  •  遥遥无期
    2021-01-01 12:12

    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} );
    }
    

提交回复
热议问题