在C#WebResponse响应上获得未经授权的错误response = request.GetResponse();

时间:2019-10-30 00:22:49

标签: c# api

在C#上执行GET请求时遇到授权错误,但是如果我使用邮递员尝试它,则返回值就很好了。

这是我的C#代码:

url = @"http://somesource.com/api/v10/" + url;
WebRequest request = WebRequest.Create(url);
request.Headers.Add("Authorization", "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds");
request.Method = "GET";
request.Timeout = TimeO; 


      try { 
           WebResponse response = request.GetResponse();
           status = ((HttpWebResponse)response).StatusDescription.ToString();


           if (status != "OK")
           Log.WriteLog(module, "Response x:: " + status);

          Stream dataStream = response.GetResponseStream();
          StreamReader reader = new StreamReader(dataStream);
          dataResponse = reader.ReadToEnd();
          reader.Close();
          dataStream.Close();
          response.Close();
      } catch (WebException ex)
        {
          dataResponse = "{\"Error\":true,\"Update\":false,\"Msg\":\"RQ x:: " + ex.Message + "\"}";
          Log.WriteLog(module, dataResponse);
      }

它返回The remote server returned an error: (401) Unauthorized.

但是当我尝试在GET请求的邮递员上使用与Authorization = "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds"相同的url +标头时,它会返回json数据。

尽管如果我不发送邮递员的标头,我会得到

{
    "detail": "Authentication credentials were not provided."
}

如果我故意将令牌设置为错误,这就是我得到的:

{
    "detail": "Invalid token."
}

与c#程序记录的内容不同。

The remote server returned an error: (401) Unauthorized.

这可能是什么原因?

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试以下代码。原始参考文献here

string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
    WebRequest request = WebRequest.Create(url);
    request.Credentials = GetCredential();
    request.PreAuthenticate = true;       

     private CredentialCache GetCredential()
        {
            string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            CredentialCache credentialCache = new CredentialCache();
            credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
            return credentialCache;
        }