Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning HTTP 403 in a WebAPI method

How do I return an HTTP 403 from a WebAPI method? I've tried throwing an HttpResponseException with HttpStatusCode.Forbidden, and I've tried

return request.CreateErrorResponse(HttpStatusCode.Forbidden, pEx);

Neither of which work. Both ALWAYS return an HTTP 200. What am I missing? It has to be something simple but I don't see it.

like image 457
jeff.eynon Avatar asked Jun 19 '13 21:06

jeff.eynon


People also ask

How do I return a 403?

When you want to respond with a HTTP 403 status code from an API and do not want the ASP.NET Core authentication logic to perform any redirect or other action, use: return StatusCode(403); // or with developer-friendly type return StatusCode(StatusCodes.

How do I return content in Web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).

Why do I get an HTTP 403 Forbidden error when connecting to my API gateway APIs from a VPC?

The HTTP 403 Forbidden error most commonly occurs when private DNS is enabled for an API Gateway interface VPC endpoint that's associated with a VPC. In this scenario, all requests from the VPC to API Gateway APIs resolve to that interface VPC endpoint.

Can we return the view from Web API method?

You don't return a View from an API controller. But you can return API data from an MVC controller. The solution would be to correct the errors, not try to hack the API controller. Constructor arguments most certainly can be used in controllers for dependency injection.


1 Answers

You might have a problem with your routing configuration. Below is a working sample. Put it in your controller and see if it works. If it doesn't, check your routing with a diagnostic tool (i.e. Cobisi Routing Assistant).

public HttpResponseMessage GetSomeString(int id)
{
    // This method is not allowed!
    return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "This method is not allowed!");
}
like image 143
Teoman Soygul Avatar answered Oct 29 '22 05:10

Teoman Soygul