How to get protocol, host, and port in .net application?

Raj
Raj
648 Points
26 Posts

how to get protocol, host, and port in asp.net?

<link href="<%=GetURL()+""+Url.Content("~/Styles/Sitecss.css") %>" rel="stylesheet" type="text/css" />
<a href="<%=GetURL()+""+Url.Action("actionname","controllername")%>">Click here</a>

In the above GetURL() is some method in backend code.

Views: 15910
Total Answered: 4
Total Marked As Answer: 2
Posted On: 25-Apr-2015 09:09

Share:   fb twitter linkedin
Answers
Brian
Brian
2376 Points
13 Posts
         

Hi,

Use follwing method:

GetURL();

For example in MVC:

<link href="<%=GetURL()+""+Url.Content("~/Styles/Sitecss.css") %>" rel="stylesheet" type="text/css" />
<a href="<%=GetURL()+""+Url.Action("actionname","controllername")%>">Click here</a>

Method GetURL() :

public static string GetURL()
{
 
string URL = "";
 
try
{
 
string Port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
 
if ((Port == null) | Port == "80" | Port == "443")
{
Port ="";
}
 
else
{
Port =":" + Port;
}
 
string Protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
 
if ((Protocol == null) | Protocol == "0")
{
Protocol ="https://";
}
 
else
{
Protocol ="https://";
}
URL = Protocol +HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + Port + "";
}
 
catch (Exception ex)
{
}
 
return URL;
}

 

Posted On: 26-Apr-2015 02:57
Rahul Kiwitech
Rahul K...
292 Points
26 Posts
         

Use this in controller

Request.Url.AbsoluteUri

This property does everything you need, all in one susinct call.

Posted On: 18-Jul-2016 05:05
Smith
Smith
2890 Points
78 Posts
         

Try this

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
Posted On: 23-Jun-2017 03:34
beginer
beginer
1544 Points
52 Posts
         

If you are in class file  then you can use this method to get the url

public static string ResolveServerUrl(string serverUrl, bool forceHttps)
    {
      if (String.IsNullOrEmpty(serverUrl))
        return serverUrl;
      if (serverUrl.IndexOf("://") > -1)
        return serverUrl;

      string newUrl = serverUrl;
      Uri originalUri = System.Web.HttpContext.Current.Request.Url;
      newUrl = (forceHttps ? "https" : originalUri.Scheme) +
          "://" + originalUri.Authority + newUrl;
      return newUrl;
    }
Posted On: 26-Jun-2018 01:07
 Log In to Chat