簡體   English   中英

遠程服務器返回錯誤:(401) Unauthorized at System.Net.HttpWebRequest.GetResponse()

[英]The remote server returned an error: (401) Unauthorized at System.Net.HttpWebRequest.GetResponse()

我正在嘗試運行以下代碼,它在 localhost IIS 上運行時工作正常,但在我的 Web 服務器 IIS 上托管時返回錯誤

錯誤:--遠程服務器返回錯誤:(401)未經授權。 在 e:\WebSite1\Default.aspx.cs 中的 _Default.btnsubmit_Click(Object sender, EventArgs e) 處的 System.Net.HttpWebRequest.GetResponse():

try
{

var webAddr = "http://serviceserver/someService";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "text/xml";
httpWebRequest.ContentLength = 0;
httpWebRequest.Method = "GET";

httpWebRequest.Credentials = new NetworkCredential("user", "password");
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new treamReader(httpResponse.GetResponseStream()))
   {
       var result = streamReader.ReadToEnd();
       Label1.Text = result;
   }
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.StackTrace);
Response.Write(ex.InnerException);
}

更新上述服務 URL 是 WCF 服務,它通過 Windows 中的傳輸憑據進行保護我試圖通過我的 Web 應用程序訪問此 URL 並將我的憑據作為網絡憑據傳遞。 當我在本地計算機上運行此 Web 應用程序時,它運行良好並返回所需的數據。 但是當我托管這個應用程序時,我得到了上述錯誤。 難道我做錯了什么。

您需要在您的服務器上查找用戶名、通行證以及它是基本的還是摘要的。 我這樣設置我的命令:

 HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
 var cache = new CredentialCache();
 cache.Add(new Uri(uri), "Digest", new NetworkCredential("administrator", "admin"));
 httpRequest.Credentials = cache;
 httpRequest.PreAuthenticate = true;
 using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
 {
    //DO CODE

 }

在代碼中實現 httpRequest 之前,您應該先在瀏覽器中檢查它。 在瀏覽器中輸入您的鏈接,看看它是否會顯示您想要的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM