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.

Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53
jeff.eynon
  • 1,296
  • 3
  • 11
  • 29

1 Answers1

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!");
}
Micah Switzer
  • 144
  • 1
  • 11
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 1
    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. – jeff.eynon Jun 20 '13 at 13:58
  • 4
    Getting invalid cast from HttpResponseMessage to String – user3953989 Apr 19 '16 at 15:27
  • how to fix the invalid cast to string? – GreyCloud May 24 '17 at 15:39
  • you always can throw a HttpResponseException(HttpStatusCode.Forbidden) instead. – huer12 Jul 02 '18 at 12:54