Question

Host vs DnsSafeHost

I need to get the host out of the Request object. Which property should I use and why?

From MSDN:

Uri.DnsSafeHost Property

A String that contains the unescaped host part of the URI that is suitable for DNS resolution; or the original unescaped host string, if it is already suitable for resolution.

vs

Uri.Host Property

A String that contains the host name. This is usually the DNS host name or IP address of the server.

My testing has been with the ASP.NET Development Server. Both of these always return localhost. Even when I put in 127.0.0.1, both return localhost.

Reading on, the DnsSafeHost property will handle IPv6 addresses, as well as Unicode to ASCII conversion if needed. It can also account for IRI and IDN. Even though I currently don't care about these things, should I just use the DnsSafeHost property to be safe?

 45  12268  45
1 Jan 1970

Solution

 54

Apply DnsSafeHost to the URL if you intend to send the resulting host name to a DNS server on your own. DNS was originally an ASCII-only protocol (and a subset of ASCII at that). Present day URL's allow character sequences in the host portion of a URL that cannot be sent directly to a DNS server. Examples are:

  • bracket-enclosed IPv6 addresses. DnsSafeHost drops the brackets.

  • Non-ASCII, non-English domain names. DnsSafeHost (optionally) uses RFC 3987 IRI to normalize the characters, and converts non-ASCII character to IDN, Punycode encoding.

  • Who knows what URLs will allow in the future? The application may well outlive our assumptions of what's okay in a URL. DnsSafeHost adds a degree of resilience there.

If you need to display the host name to the user, use the Host property instead.

2009-08-03