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.
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.
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).
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.
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.
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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With