0

In my WebAPI, if I detect a Bad Authorisation I use the following;

   [HttpPost]
   public HttpResponseMessage CustomerQuotationComplete(Guid apiKey, int EnquiryId, int SiteId, bool accepted)
   {
      if (IsRequestAuthorized())
      {
        ...
      }
      else
      {
          var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Bad Authentication" };
          throw new HttpResponseException(msg);
      }
    }

However what I am actually receiving a 302 Found response, not a 401 Unauthorized.

So what am I doing wrong?

Matt
  • 1,596
  • 2
  • 18
  • 32

3 Answers3

5

You can return Unauthorized response

[HttpPost]
   public IHttpActionResult CustomerQuotationComplete(Guid apiKey, int EnquiryId, int SiteId, bool accepted)
   {
      if (IsRequestAuthorized())
      {
        ...
      }
      else
      {
          return this.Unauthorized();
      }
    }
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
0

Try to return your message instead of thowing out an exeption:

var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Bad Authentication" };
return msg;
Benjamin Soulier
  • 2,223
  • 1
  • 18
  • 30
  • That does the same as the above. – Matt Aug 16 '16 at 12:15
  • Having a similar code, it does return an http 401. Try to see if you are not using any [Global Filters or OWIN specifics](http://stackoverflow.com/questions/20149750/owin-unauthorised-webapi-call-returning-login-page-rather-than-401) for login or other purpose that would be called bedore your controller method. Give a try to an simple empty project too, to validate taht this has to do with your project setup. – Benjamin Soulier Aug 16 '16 at 12:24
0

Your code looks right, however when you have Owin for authenticating users all 401 responses seems to be intercepted to redirected to microsoft login page. In this case you should see the login url in the response.

If you disable owin authentication your api will return 401 (ad it works even returning an object and without throwing exceptions)

sample call from fiddler

Grappachu
  • 1,259
  • 13
  • 21