Workaround for generating absolute URLs without port number

Update: You can now set the aspnet:UseHostHeaderForRequestUrl appSetting to true which effectively solves this problem. This can be done by adding a Configuration Variable to your application with the corresponding key and value. You can read more about it here and feel free to shoot us an email if you continue to see this issue.

Our application web servers run behind load balancers that proxy requests to multiple web servers running multiple apps. We use port numbers on the web servers to handle this. This causes problems for some .NET url helpers.

For instance Request.Url will not return the expected public URL.

You'll have to work around this limitation in some way. Below is an example of a URL builder that returns a correct absolute url for your application.

public static string ToPublicUrl(this UrlHelper urlHelper, Uri relativeUri)
{
    var httpContext = urlHelper.RequestContext.HttpContext;

    var uriBuilder = new UriBuilder
    {
            Host = httpContext.Request.Url.Host,
            Path = "/",
            Port = 80,
            Scheme = "http",
    };

    if (httpContext.Request.IsLocal)
    {
        uriBuilder.Port = httpContext.Request.Url.Port;
    }

    return new Uri(uriBuilder.Uri, relativeUri).AbsoluteUri;
}

Recent Discussions

21 Sep, 2014 12:33 AM
20 Sep, 2014 01:28 AM
19 Sep, 2014 01:05 AM
16 Sep, 2014 11:22 PM
15 Sep, 2014 12:55 PM