0

I have a variable containing a URL.

string url;

It may contain loop-back host name. For example, its value could be the following:

http://localhost/x

I want to ensure that the URL will be usable from a different computer that has access to the current computer. If it is a loop-back URL, this won't work.

For example, if the current computer's domain name is webserver.company.local, how can I programmatically replace loop-back URLs' host names this value?

Note that this is for an ASP.NET application, but I'm also interested in a general-purpose solution.

Sam
  • 40,644
  • 36
  • 176
  • 219

1 Answers1

1

One approach to this problem is to do the following steps:

  1. Determine if the URL is a loop-back. If so, proceed. One way to do this is using Uri.IsLoopback.
  2. Determine the current computer's DNS host name. This can be done using the static Dns class.
  3. Replace the host name portion of the URL with the current computer's one. This can be done using UriBuilder.

Given this method signature:

Uri MakeExternallyUsable(Uri uri)

Here are two implementations to achieve the desired result:

General Solution

Dns.GetHostName can be used to get the possibly fully-qualified host name. However, I think it would be more robust to use the fully-qualified host name. A mechanism to do this is suggested in this answer.

If you use this approach, make sure to consider the permissions required and the possible exceptions.

if (uri.IsLoopback)
{
    var builder = new UriBuilder(uri)
    {
        Host = Dns.GetHostEntry("LocalHost").HostName
    };

    return builder.Uri;
}
else
    return uri;

ASP.NET

In the context of an ASP.NET response, I think the current computer's host name may not necessarily be the same as the one used by the requester. Also, the computer may have multiple different associated host names. Because of these, getting the host name from the HTTP request's URL seemed suitable to me. Modify the above implementation to use this host name:

/*Get HTTP request*/.Url.Host
Community
  • 1
  • 1
Sam
  • 40,644
  • 36
  • 176
  • 219