MSDN Library

Home > Library > System > System.Net > System.Net.Security

NetworkCredential Class

Represents a user's network credentials.

Namespace: System.Net

Assembly: System (in System.dll)

Remarks

The NetworkCredential class stores the username, password, and domain associated with a network user. This information is used by network protocols to authenticate the user. For example, the HttpClient and FtpWebRequest classes can use NetworkCredential objects to authenticate with remote servers.

When you create a NetworkCredential object, you can specify the username, password, and domain as parameters. The username and password are required, while the domain is optional.

The properties of the NetworkCredential class are read-only after the object has been created. To modify credentials, you must create a new NetworkCredential object.

Constructors

Properties

  • Domain string

    Gets the domain associated with the network credential.

  • Password string

    Gets the password associated with the network credential.

  • UserName string

    Gets the user name associated with the network credential.

Example

The following code example demonstrates how to create a NetworkCredential object and use it to authenticate with a Web resource.

// Using System.Net;
// Using System.Net.Http;

// Create a new NetworkCredential object
NetworkCredential credentials = new NetworkCredential("myusername", "mypassword", "mydomain.com");

// 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 to a protected resource
        HttpResponseMessage response = await client.GetAsync("https://protected.example.com/data");
        response.EnsureSuccessStatusCode(); // Throw an exception if the status code is not 2xx

        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"Request exception: {e.Message}");
    }
}

See Also