Returning http status code from Web Api controller

前端 未结 13 1493
一生所求
一生所求 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:44

    In MVC 5, things got easier:

    return new StatusCodeResult(HttpStatusCode.NotModified, this);
    
    0 讨论(0)
  • 2020-11-27 10:44
    public HttpResponseMessage Post(Article article)
    {
        HttpResponseMessage response = Request.CreateResponse<Article>(HttpStatusCode.Created, article);
    
        string uriToTheCreatedItem = Url.Route(null, new { id = article.Id });
        response.Headers.Location = new Uri(Request.RequestUri, uriToTheCreatedItem);
    
        return response;
    }
    
    0 讨论(0)
  • 2020-11-27 10:46

    .net core 2.2 returning 304 status code. This is using an ApiController.

        [HttpGet]
        public ActionResult<YOUROBJECT> Get()
        {
            return StatusCode(304);
        }
    

    Optionally you can return an object with the response

        [HttpGet]
        public ActionResult<YOUROBJECT> Get()
        {
            return StatusCode(304, YOUROBJECT); 
        }
    
    0 讨论(0)
  • 2020-11-27 10:49

    Another option:

    return new NotModified();
    

    public class NotModified : IHttpActionResult
    {
        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage(HttpStatusCode.NotModified);
            return Task.FromResult(response);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:51

    If you need to return an IHttpActionResult and want to return the error code plus a message, use:

    return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Error message here"));
    
    0 讨论(0)
  • 2020-11-27 10:51

    An update to @Aliostads answer using the more moden IHttpActionResult introduced in Web API 2.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results#ihttpactionresult

    public class TryController : ApiController
    {
        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);
                // If you would like to return a Http Status code with any object instead:
                // return Content(HttpStatusCode.InternalServerError, "My Message");
            }
            return Ok(user);
        }
    }
    
    0 讨论(0)
提交回复
热议问题