Generating Links In MVC with Port Translation Backend

Written By : Lam Chan

I worked in network / server environment where the url requested was redressed by the time the web server received the payload at the network layer.  So here is an example, the user types in the user http://www.yourdomain.com/home/blog, by the time the payload reached the webserver, the network hardware was directing the package internally to http://10.10.100.147:5600/home/blog.  This caused an issue for me because the UrlHelpers in the MVC stack generates absolute links based off of the Uri information that was captured from the request.  Luckily, the header information on these packets also contain the original url request format.  With a little extension method, youc an easily generate public facing links on your website even if your network layer in your collocation is not conventional or ideal.  Here is the extension method that attaches on to the UrlHelper class with the same method signature found in Link().

 

    public static class UrlHelperExtensions
    {
        public static Regex domainRegex = new Regex("(?<domain>http(s)*://([a-zA-Z0-9:-])+)");

        public static string PublicLink(this UrlHelper urlHelper, string routeName, object routeValues)
        {
            var match = domainRegex.Match(urlHelper.Request.RequestUri.OriginalString);
            if (match.Success)
            {
                var publicDomain = match.Groups["domain"].Value;
                var path = domainRegex.Replace(urlHelper.Link(routeName, routeValues), string.Empty);

                return publicDomain + path;
            }

            return urlHelper.Link(routeName, routeValues);
        }
    }

Tags: , , ,

No comments yet.

Post your comment