C# 如何验证 WebClient 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1883655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I authenticate a WebClient request?
提问by smartdirt
I am making a call to a page on my site using webclient. I'm trying to get the result of the webpage put into a pdf so I am trying to get a string representation of the rendered page. The problem is that the request is not authenticated so all I get is a login screen. I have sent the UseDefaultCredentials property to true but I still get the same result. Below is a portion of my code:
我正在使用 webclient 调用我网站上的页面。我正在尝试将网页的结果放入 pdf,因此我正在尝试获取呈现页面的字符串表示形式。问题是请求没有经过身份验证,所以我得到的只是一个登录屏幕。我已将 UseDefaultCredentials 属性设置为 true,但仍然得到相同的结果。下面是我的代码的一部分:
WebClient webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
webClient.UseDefaultCredentials = true;
return Encoding.UTF8.GetString(webClient.UploadValues(link, "POST",form));
采纳答案by John Saunders
What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient
request.
您使用的是哪种身份验证?如果是 Forms 身份验证,那么充其量只能找到 .ASPXAUTH cookie 并将其传递到WebClient
请求中。
At worst, it won't work.
在最坏的情况下,它不会起作用。
回答by Ryan Alford
You need to give the WebClient object the credentials. Something like this...
您需要为 WebClient 对象提供凭据。像这样的东西...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
回答by Rouletabille
Public Function getWeb(ByRef sURL As String) As String
Dim myWebClient As New System.Net.WebClient()
Try
Dim myCredentialCache As New System.Net.CredentialCache()
Dim myURI As New Uri(sURL)
myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
myWebClient.Encoding = System.Text.Encoding.UTF8
myWebClient.Credentials = myCredentialCache
Return myWebClient.DownloadString(myURI)
Catch ex As Exception
Return "Exception " & ex.ToString()
End Try
End Function