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 know the 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 www.rajeeshcv.com:4566 instead of just www.rajeeshcv.com.
After googling for some time I came across the solution posted Appharbor 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.
According to the MSDN documentation
IsLocalproperty returns true if the IP address of the request originator is 127.0.0.1 or if the IP address of the request is the same as the server’s IP address.
In my case I think
IsLocal was true (I really don’t the exact reason!!!). So instead of using the appharbor code snippet I came across a code from FunnelWeb which does the same (HttpRequestExtensions.cs)
Here is my version of that code
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).