.NET
URL Parsing
Networking
Web Development
Programming

.NET - Get protocol, host, and port

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

.NET provides several approaches to retrieving components of a request URL, such as protocol, host, and port. These elements are crucial for applications that interact heavily with web resources, as they allow developers to manipulate and utilize URLs effectively. In this article, we will explore how to access and use these URL components within the .NET framework.

Accessing URL Components in .NET

The .NET framework offers a range of classes and methods that make it easy to parse and work with URLs. The `Uri` class is one of the primary tools for this purpose.

`Uri` Class

The `Uri` class provides properties and methods to manipulate Uniform Resource Identifiers (URIs). It is part of the `System` namespace and represents a URI and provides easy access to its parts.

Example: Using the `Uri` Class

  • `Scheme`: This property retrieves the protocol of the URL, e.g., `http`, `https`.
  • `Host`: This property retrieves the host (domain or IP address) of the URL, e.g., `example.com`.
  • `Port`: This property retrieves the port number of the URL. If no port is specified in the URL, it returns the default port for the protocol.
  • `Scheme`: Represents the request's protocol (e.g., `http`, `https`).
  • `Host`: The `Host` property of `HttpRequest` returns an object that contains both the host and port. Hence, you need to access the `Host.Host` and `Host.Port` separately.
  • Port: Since the port may not always be included in the request, it is important to handle null values. By default, the port is usually 80 for HTTP and 443 for HTTPS if not explicitly defined.
  • Absence of Explicit Port: Some URLs might not specify a port. In such cases, the application should infer the ports based on protocol standards.
  • IPv6 Addresses: If dealing with IPv6 addresses, which might include enclosed square brackets, ensure proper handling in parsing.
  • Local Development: While developing locally, remember that the server might be running on a non-standard port. Always verify the `Host.Port` in your configuration.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.