C#HttpWebRequest返回错误403

时间:2016-03-17 19:36:17

标签: c# asp.net-mvc web-services http httpwebrequest

我的应用程序的以下部分存在问题,它返回错误403作为HttpWebRequest的响应。你能告诉我为什么会出现这个错误吗?

                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 

但是,当我使用以下命令在powerShell中发送相同的请求时,我得到了成功响应:

> $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

1 个答案:

答案 0 :(得分:1)

对不起,如果这没有提示答案;我不会让我发表评论。

您确定webServiceServerName + uri评估的价值为a.k.a." APIURL.Domanin.com"?也许该代码巧合地试图与服务器进行通信,而该服务器不是您之后的服务器,它具有另一组认证/授权规则(HTTP-403表示"禁止")