Returning http status code from Web Api controller

前端 未结 13 1568
一生所求
一生所求 2020-11-27 10:01

I\'m trying to return a status code of 304 not modified for a GET method in a web api controller.

The only way I succeeded was something like this:

p         


        
13条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 10:28

    For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult. You can then return a built in IHttpActionResult implementation like Ok, BadRequest, etc (see here) or return your own implementation.

    For your code, it could be done like:

    public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
    {
        var user = new DataEntities().Users.First(p => p.Id == userId);
        if (user.LastModified <= lastModifiedAtClient)
        {
            return StatusCode(HttpStatusCode.NotModified);
        }
        return Ok(user);
    }
    

提交回复
热议问题