Rajeeshcv.com

The title might be misleading but I will explain why we shouldn’t use the Request.Url in any asp.net application directly.

If you are writing an web application and you don’t where it is going to be deployed, environment of the server where it is getting deployed, then it is better not to use Request.Url it directly.

This blog is running on a home grown blog engine, which is written using asp.net MVC 3. For implementing some of the functionalities like generating sitemap.xml I had to get the root of the url(i.e. without any path). So I used the Request.Url.GetLeftPart(UriPartial.Authority) method and it worked perfectly on my local machine even when it is deployed my local machine IIS server. When I deployed my blog engine to Appharbor environment, the generated sitemap.xml has a URL with port number like http://www.rajeeshcv.com:4566 instead of just http://www.rajeeshcv.com.

Why?

After googling for some time I came across the solution posted appharbor.com knowledge base - workaround for generating absolute urls without port number. In their environment there are load balancers which sits in front on the webserver, which uses a specific port number for contacting the server where the application is running. Below is a simple pictorial representation of that

So whenever we try to get Request.Url, application will get the actual request Url received by that webserver, which will have the port number also.

How to solve it

Appharbor has provided a code snippet in the same article but it didn’t worked for me, I was still getting port number in the generated Url. My assumption is that, there is condition check for ignoring the local request so that it will work correctly in the local development environment.

Conclusion

IMHO this is a limitation with .Net framework itself because here we have to modify the behaviour of the framework class to achieve what we really want . If there is way in which the IIS web server can detect the topology on which it is running, then the HttpRequest.Url could be implemented correctly. So that the developer need not to worry about the deployment scenarios(at least in this simple case).