Create URL dynamically in ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with Leave a comment on Create URL dynamically in ASP.NET

Utility program to find that current connection is secured or not, connection is http or https. Create dynamic URL in ASP.NET. Example of Page.ResolveUrl() in ASP.Net.

Hi friend,

I am writing this article after very long duration. Have lots of tips to share from my toolbox, so here few about the dynamic creation of URL in ASP.NET:

lets say, you have to register the javascript file from code behind, then you may need a full path for that js file in format “http://yourdomain/jsfolder/jsfilename”

one way to achieve this is like :

"http://" Request.ServerVariables["HTTP_HOST"] + "/jsfolder/jsfilename.js";

In above snap you can see that HTTP_HOST is used. This server variable returns the address of your domain. Still, above code is not 100% functional.protocol may be http or https.

To get the exact protocol, we need to check that connection is secured or not.
below is small utility to find that connection is secured or not:

        /// <summary>
        /// Gets if the url is secure or not
        /// </summary>
        private bool isSecureURL
        {
            get
            {
                // Check the request
                if (HttpContext.Current.Request.IsSecureConnection ||
                    (HttpContext.Current.Request.
                     ServerVariables["HTTPS"] != null &&
                    HttpContext.Current.Request.
                    ServerVariables["HTTPS"].ToLower() == "on"))
                    return true;
                if ((!string.IsNullOrEmpty(HttpContext.Current.Request.
                    ServerVariables["HTTP_HOST"].ToString())) &&
                    (HttpContext.Current.Request.
                      ServerVariables["HTTP_HOST"].ToString().
                      EndsWith("443")))
                    return true;
                // url is not secure:
                return false;
            }
        }

In code check whether above property returns true or false. if its true then use https or use http protocol.

In my application, the above code behaves unexpectedly.
in case of http protocol, every thing is fine; but in case of https protocol, the base path of website repeats like below line.

https://yourdomainhttps://yourdomain/jsfolder/jsfilename


So, the another and simplest approach i have used and which is working great is the ResolveUrl method of the page.
so the above code snap can easily written like :
Page.ResolveUrl(“~/jsfolderName/jsfileName.ja”);
The advantage of above approach is that no need to find the host name or protocol, every thing is taken care.
While reading, i found one good article on using this approach and its advantage at this site.

Related posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.