10

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.

3

1 Answer 1

3

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!");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Teoman, that does work. Oddly, it seems to be some sort of interaction with DotNetOpenAuth. My web api is an endpoint secured with DotNetOpenAuth. If I call my method without going through the DotNetOpenAuth verification, I get a 403. However, If I call it by going through DotNetOpenAuth verification, and the verificatoin fails (which is the situation I want to return a 403 with), the same line of code you suggested runs, however no matter what I get a 200 back. So I guess I'll have to re-post with a dotnetopenauth tag.
Getting invalid cast from HttpResponseMessage to String
how to fix the invalid cast to string?
you always can throw a HttpResponseException(HttpStatusCode.Forbidden) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.