Search code examples
c#asp.net-web-apihttprequestfiddlerhttp-status-code-302

Fiddler reporting different response code from API to that received by the calling app


I am calling an API that is hosted in Azure API management. The API is configured to use Azure Active Directory for authentication, and as such should produce a 302 redirect response when called with no authorisation header.

This is my call:

var request = (HttpWebRequest)WebRequest.Create("MyApiEndPoint");
request.ContentType = "text/html; charset=utf-8";
request.Headers.Add("Ocp-Apim-Subscription-Key", model.SubKey);

var response = (HttpWebResponse)request.GetResponse();

When I watch the call in fiddler I can indeed see the 302 redirect as the response:

enter image description here

However in my calling app I am getting back a 401 response.

Can anybody explain what is happening here?


Solution

  • You have not set AllowAutoRedirect to false on your request.

    The 302 is a redirect, so your request does not pass it as a response but issues a new request on the redirection resource then yields you the result of that other request.

    Side note: issuing a 302 on a missing authorization may be fine for a user navigating a web page through a browser, in order to show him a custom login page. But for an API, it may be better to directly yield a 401.