Search code examples
c#asp.net-mvcweb-serviceshttphttpwebrequest

C# HttpWebRequest returns error 403


I have an issue with the following section of my application that returns error 403 as a response of the HttpWebRequest. Can you please let me know why it get this error?

                string url = "http://" + webServiceServerName + uri + "?extendedInfo=2";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/json";

                //Failed tries to fix this error 403, non of these fix the issue
                request.UserAgent = "[AnyWordThatIsMoreThan5Char]";
                request.UseDefaultCredentials = true;
                request.Accept = "*/*";


                //Get the headers associated with the request.
                WebHeaderCollection myWebHeaderCollection = request.Headers;
                //Add Custom header fields
                myWebHeaderCollection.Add("api-version","1.0");
                myWebHeaderCollection.Add("auth-key","XYZ");


                // Gets the stream associated with the response.            
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // response contains error 403 

However, when I send the same request in powerShell using following commands, I get the success response:

> $headers = @{"api-version"="1.0"; "auth-key"="XYZ"}
> Invoke-RestMethod -Uri "http://APIURL.Domanin.com?extendedinfo=2" -Headers $header -ContentType "application/json" -Method Get

Service           : Configured
Version           : 6.1.0.1
Transfer Database : Available
Logging Database  : Available
Client Database   : Configured
Fileshare         : Available

Solution

  • Sorry if this doesn't hint the answer; SO won't let me comment.

    Are you sure that webServiceServerName + uri evaluates to a value a.k.a. "APIURL.Domanin.com"? Maybe that code coincidentally ends up attempting to communicate to the server that isn't the one you're after, which has another set of authentication/authorization rules (HTTP-403 means "forbidden").