Interface ICredentials
Represents the credentials that are sent to a server to authenticate an HTTP request.
Namespace: System.Security.Authentication
Assembly: System (in System.dll)
Syntax
Remarks
The ICredentials interface is used to represent the credentials that are sent to a server to authenticate an HTTP request. The NetworkCredential class is a concrete implementation of the ICredentials interface.
When you are making an HTTP request to a server that requires authentication, you can use an object that implements the ICredentials interface to provide the necessary credentials. This object is then passed to the Credentials property of the HttpClientHandler or WebClient class.
The ICredentials interface has a single method, GetCredential, which is responsible for returning the appropriate NetworkCredential object for a given URI.
Methods
GetCredential
Returns a NetworkCredential object that contains the credentials for the specified URI and authentication type.
Parameters
- requestUri: A
Uriobject that specifies the URI to which the request is being made. - authType: A string that specifies the authentication type.
Return Value
A NetworkCredential object that contains the credentials for the specified URI and authentication type.
Remarks
This method is called by the .NET Framework to obtain the credentials to use when making an HTTP request.
See Also
Example
The following example demonstrates how to use the NetworkCredential class, which implements ICredentials, to set credentials for an HTTP request.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
// Create a NetworkCredential object
ICredentials credentials = new NetworkCredential("username", "password");
// Create an HttpClientHandler and set its Credentials property
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = credentials;
// Create an HttpClient using the handler
using (HttpClient client = new HttpClient(handler))
{
try
{
// Make an HTTP request
HttpResponseMessage response = await client.GetAsync("https://example.com/api/data");
response.EnsureSuccessStatusCode(); // Throw an exception if the status code is not success
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}