[ACCEPTED]-How do i send a "forbidden" response in my Web API 2 solution?-asp.net-web-api2

Accepted answer
Score: 11

You can use an HttpResponseMessage like 3 so:

public HttpResponseMessage Get(string id, string securityToken)
    var forbidden = true;
    if (forbidden)
        return this.Request.CreateResponse(HttpStatusCode.Forbidden);
    return Ok(userRepository.LoadAll());

Using HttpResponseMessage allows you 2 to return OK (an HTTP 200) with content, or 1 an error.

Score: 9


return StatusCode(HttpStatusCode.Forbidden);


return Content(HttpStatusCode.Forbidden, "message");


return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "message");

See this example if you would like a 2 custom controller to have Forbidden() implemented just 1 like BadRequest() or any other response.


Score: 6

Typically you'd do the ValidateToken type call in an 6 ActionFilterAttribute, returning the forbidden at that time, long 5 before the Get method was called on the controller. You'd 4 then apply that attribute to the controller 3 or action method (or register it as a global 2 action filter attribute if you need to authorize 1 ALL calls).

More Related questions