[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

IHttpActionResult:

return StatusCode(HttpStatusCode.Forbidden);

Or:

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

HttpResponseMessage:

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.

https://stackoverflow.com/a/28361376/3850405

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