.NET - Get protocol, host, and port

Brian
Brian
Participant
570 Points
75 Posts

Hi,

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

Views: 8290
Total Answered: 4
Total Marked As Answer: 1
Posted On: 25-Apr-2015 09:09

Share:   fb twitter linkedin
Answers
Brian
Brian
Participant
570 Points
75 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...
Participant
100 Points
40 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
Participant
374 Points
112 Posts
         

Try this

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
Posted On: 23-Jun-2017 03:34
beginer
beginer
84 Points
32 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