Returning Http Status Code from Web API Controller

Returning http status code from Web Api controller

I did not know the answer so asked the ASP.NET team here.

So the trick is to change the signature to HttpResponseMessage and use Request.CreateResponse.

[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
return request.CreateResponse(HttpStatusCode.OK, user);
}

Getting controller return status code for web api

The OnActionExecuting is executed before the action is run. The status code does only provide meaningful information after the action is run. Even if there is a response object available that you could get the status code from, the real status code is only available

Therefore, you could use the OnActionExecuted method to access the status code that was set by the action.

For details, see this link. Though this link describes the behavior of filters for MVC, the basic mechanism is the same for the filters in Web API.

How to return both custom HTTP status code and content?

You can use ContentResult:

return new ContentResult() { Content = myContent, StatusCode = myCode };

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);



You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ← Http status code 200
  • return Created() ← Http status code 201
  • return NoContent(); ← Http status code 204

Client Error:

  • return BadRequest(); ← Http status code 400
  • return Unauthorized(); ← Http status code 401
  • return NotFound(); ← Http status code 404


More details:

  • ControllerBase Class (Thanks @Technetium)
  • StatusCodes.cs (consts aviable in ASP.NET Core)
  • HTTP Status Codes on Wiki
  • HTTP Status Codes IANA

.NET Core Web API: return a custom HTTP status code with Content Type application/problem+json

The code that generates the ProblemDetails response isn't aware of the 410 status-code, so it doesn't have an associated Link and Title property to use when building the response object. To add this awareness, configure ApiBehaviorOptions in ConfigureServices, like this:

services.Configure<ApiBehaviorOptions>(options =>
{
options.ClientErrorMapping[410] = new ClientErrorData
{
Title = "Gone",
Link = "https://tools.ietf.org/html/rfc7231#section-6.5.9"
};
});

ClientErrorMapping is a dictionary of int (status-code) to ClientErrorData. Note that the value I've used for Link above does point to the correct section of the RFC.



Related Topics



Leave a reply



Submit