使用英语阅读

通过


NetworkCredential.GetCredential 方法

定义

为指定的身份验证类型返回 NetworkCredential 类的一个实例。

重载

GetCredential(String, Int32, String)

针对指定的主机、端口和身份验证类型返回 NetworkCredential 类的实例。

GetCredential(Uri, String)

针对指定的统一资源标识符 (URI) 和身份验证类型返回 NetworkCredential 类的实例。

GetCredential(String, Int32, String)

Source:
NetworkCredential.cs
Source:
NetworkCredential.cs
Source:
NetworkCredential.cs

针对指定的主机、端口和身份验证类型返回 NetworkCredential 类的实例。

C#
public System.Net.NetworkCredential GetCredential (string host, int port, string authenticationType);
C#
public System.Net.NetworkCredential GetCredential (string? host, int port, string? authenticationType);

参数

host
String

对该客户端进行身份验证的主机。

port
Int32

与客户端通信的 host 上的端口。

authenticationType
String

AuthenticationType 属性中定义的所请求的身份验证类型。

返回

指定的主机、端口和身份验证协议的 NetworkCredential;如果指定的主机、端口和身份验证协议没有可用的凭据,则为 null

实现

注解

的值 authType 对应于 IAuthenticationModule.AuthenticationType 属性。

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GetCredential(Uri, String)

Source:
NetworkCredential.cs
Source:
NetworkCredential.cs
Source:
NetworkCredential.cs

针对指定的统一资源标识符 (URI) 和身份验证类型返回 NetworkCredential 类的实例。

C#
public System.Net.NetworkCredential GetCredential (Uri uri, string authType);
C#
public System.Net.NetworkCredential GetCredential (Uri? uri, string? authenticationType);

参数

uri
Uri

客户端为其提供身份验证的 URI。

authTypeauthenticationType
String

AuthenticationType 属性中定义的所请求的身份验证类型。

返回

NetworkCredential 对象。

实现

示例

下面的代码示例使用 GetCredential 方法检索 NetworkCredential 指定 URI 的对象。

C#
// Create an empty instance of the NetworkCredential class.
NetworkCredential myCredentials = new NetworkCredential(userName,password);
// Create a webrequest with the specified URL.
WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentials.GetCredential(new Uri(url),"");
Console.WriteLine("\n\nUser Credentials:- UserName : {0} , Password : {1}",myCredentials.UserName,myCredentials.Password);
// Send the request and wait for a response.
Console.WriteLine("\n\nRequest to Url is sent.Waiting for response...Please wait ...");
WebResponse myWebResponse = myWebRequest.GetResponse();
// Process the response.
   Console.WriteLine("\nResponse received successfully");
// Release the resources of the response object.
myWebResponse.Close();

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0