Search code examples
c#authorizationhttpwebrequest

Authorization Header is not properly updated in my HttpWebRequest


Strange thing is going on with my HttpWebRequest... I want to write a function that updates authorization header if needed (when we get 401 in response). So basically something like this:

try
{
    request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + BadToken);
    return request.GetResponse();
}
catch (Exception e)
{
    if (e is WebException) 
    {
        var ex = (e as WebException);
        var status = (ex.Response as HttpWebResponse)?.StatusCode;

        if (status == HttpStatusCode.Unauthorized)
        {
            request.Headers.Set(HttpRequestHeader.Authorization, "Bearer " + CorrectToken);
            return request.GetResponse();
        }
    }
    return null;    
}

Unfortunately I still get a 401. But if I replace BadToken with CorrectToken at the first line, I get 200 in first try. So it seems like the header is not updated... I checked in the debugger and I can see that value is changed, but the behaviour speaks for itself...

What is going on in here?


Solution

    1. Multiple calls to GetResponse return the same response object; the request is not reissued. Refer this link: https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.getresponse?view=netframework-4.8

    2. Make a new instance of HttpWebRequest in the catch block and issue the request with new token.