如何从ASP.NET代码中获取当前URL

dot*_*lop 10 asp.net

我的应用程序托管在不同的服务器上,我想获取当前服务器上页面的URL.

你怎么能在代码中获得这个属性?

kob*_*obe 26

string url = HttpContext.Current.Request.Url.AbsoluteUri;
Run Code Online (Sandbox Code Playgroud)

http://thehost.com/dir/Default.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
Run Code Online (Sandbox Code Playgroud)

/dir/Default.aspx

string host = HttpContext.Current.Request.Url.Host;
Run Code Online (Sandbox Code Playgroud)

thehost.com

  • @Pranav-BitWiser HttpContext.Current.Request.Url 返回 System.Uri。以下是所有 Uri 属性的摘要:http://blog.jonschneider.com/2014/10/systemuri-net-framework-45-visual-guide.html (2认同)

Sir*_*our 5

string MyUrl = HttpContext.Current.Request.Url.AbsoluteUri
Run Code Online (Sandbox Code Playgroud)


Pra*_*sad 5

string path = HttpContext.Current.Request.Url.AbsolutePath;


IMM*_*TAL 5

从代码隐藏文件获取URL的另一种方法

public string FullyQualifiedApplicationPath
{
    get
    {
        //Return variable declaration
        var appPath = string.Empty;

        //Getting the current context of HTTP request
        var context = HttpContext.Current;

        //Checking the current context content
        if (context != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}",
                                    context.Request.Url.Scheme,
                                    context.Request.Url.Host,
                                    context.Request.Url.Port == 80
                                        ? string.Empty
                                        : ":" + context.Request.Url.Port,
                                    context.Request.ApplicationPath);
        }

        if (!appPath.EndsWith("/"))
            appPath += "/";

        return appPath;
    }
}
Run Code Online (Sandbox Code Playgroud)

检查此链接,您将获得更多信息.