2014-01-07 37 views
0

我想用httpwebrequest的Forms Authenication,但我似乎沒有任何成功。這是我在做什麼:HttpWebRequest和認證

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

request.Method = WebRequestMethods.Http.Get; 

// Authentication items ------------------------------------------- 
request.UseDefaultCredentials = false; 
request.PreAuthenticate = true; 

// Attempt to set username and password: 
CredentialCache cc = new CredentialCache(); 
cc.Add(
new Uri(url), 
"Basic", 
new NetworkCredential("username", "validpassword", "domain") 
); 
request.Credentials = cc; 

request.AllowAutoRedirect = true; 
request.KeepAlive = true; 
request.Timeout = 10000; 
CookieContainer cookieContainer = new CookieContainer(); 
request.CookieContainer = cookieContainer; 

// request html 
response = (HttpWebResponse)request.GetResponse(); 

問題是,即使有一個有效的密碼和域用戶名,這總是拋出一個異常。

任何人都可以幫忙嗎?

NOTES:

  • 異常類型:引發WebException
  • 異常消息: 「遠程服務器返回錯誤:(401)未授權」
  • 異常狀態:協議
  • 錯誤異常發生在:response =(HttpWebResponse)request.GetResponse();
  • 異常堆棧跟蹤:無 ...對不起
+0

我敢肯定有人可以幫助你,如果告訴我們被拋出什麼異常,也許一個堆棧跟蹤? – sh1rts

回答

1

我添加憑據HttpWebRequest的。

myReq.UseDefaultCredentials = true; 
    myReq.PreAuthenticate = true; 
    myReq.Credentials = CredentialCache.DefaultCredentials; 

我想知道您遇到的401錯誤的子狀態代碼。 401錯誤包含以下子狀態代碼:

401.1: Access is denied due to invalid credentials. 
401.2: Access is denied due to server configuration favoring an alternate authentication method. 
401.3: Access is denied due to an ACL set on the requested resource. 
401.4: Authorization failed by a filter installed on the Web server. 
401.5: Authorization failed by an ISAPI/CGI application. 
401.7: Access denied by URL authorization policy on the Web server. 

由於該項目運作良好您的機器上,我懷疑這是一個進程標識問題。默認情況下,IIS 6.0中的應用程序池使用「網絡服務」作爲其身份。此帳戶受到限制,因此您可能會遇到拒絕訪問問題。

出於故障排除的目的,請嘗試將應用程序池的標識更改爲「本地系統」。如果此方法可以解決此問題,請將標識更改回「網絡服務」,並向要讀取/寫入的xml文件授予讀/寫權限。

關於如何更改應用程序池的標識,請參考以下步驟:

1. Open IIS manager (Start | Control Panel | Administrative Tools | Internet Information Services Manager). 
2. Expand the 「Application Pools」 node. 
3. Right click the application pool which your project is using, and then select 「Properties」. 
4. Click 「Identity」 tab. 
5. Choose 「Local System」 in the Predefined dropdown list. 

有關如何授予權限的文件時,請按照下列步驟操作:

1. Open Windows Explorer. 
2. Right click the file, and then select "Properties". 
3. Click the "Security" tab. 
4. Add "Network Service" in access list and check "Modify", "Read", and "Write" for it. 

此外,其他文件也可能導致此問題,您可以使用Filemon來監視任何訪問文件否認問題。

FileMon的爲Windows v7.04 http://www.microsoft.com/technet/sysinternals/FileAndDisk/Filemon.mspx

+0

如何從WebException類型獲取子狀態碼? –

+0

請參閱http://msdn.microsoft.com/en-us/library/system.net.webexception.status(v=vs.110).aspx –