在 C# WebRequest 中使用 HTTP 身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/707888/
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
Using HTTP Authentication with a C# WebRequest
提问by The.Anti.9
I want to make a web request to a page that needs authenticating. How would I go about doing this? I found something that said possibly to use the Credentials property, but I'm not sure how to use it.
我想向需要身份验证的页面发出 Web 请求。我该怎么做呢?我发现了一些可能使用 Credentials 属性的内容,但我不确定如何使用它。
采纳答案by Mehrdad Afshari
Assign a new NetworkCredential
instance to the Credentials
property:
NetworkCredential
为该Credentials
属性分配一个新实例:
webClient.Credentials = new NetworkCredential("Mehrdad", "Password");
回答by Adrian Russell
It is also possible to authenticate automatically with. This will use the credentials of the currently logged on user.
也可以自动进行身份验证。这将使用当前登录用户的凭据。
webClient.Credentials = CredentialCache.DefaultCredentials
回答by ikutsin
Basic auth example:
基本身份验证示例:
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html
http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html