代码后台如何获取SharePoint当前页面的完整URL

23
8个回答

35

您仍然可以获取HttpContext,然后使用HttpContext.Current.Request.Url

SPContext.Current.Web是围绕页面的SPWeb,因此它的URL是Web的URL,而不是页面的URL。


7
为了明确,使用的完整参数是 System.Web.HttpContext.Current.Request.Url。 - Peter Jacoby
2
是的,HTTPContext类在System.Web命名空间中。 - Yuliy
5
如果您在使用ManagedPaths和/_layouts/应用程序页面,请注意。例如/sites/1/_layouts/page.aspx将变为/_layouts/page.aspx。请注意细节。 - HaavardMeling
1
只想强调一下最后的评论(关于_layouts)。我自己也被它卡住了。HttpContext.Current.Request.RawUrl将给出真实的URL(即在浏览器地址栏中看到的内容),但不会包含协议、主机或端口。可能是Server.Transfer或其中的某些内容。 - Swanny

9

3
尝试一下:SPContext.Current.Web.Url +"/"+ SPContext.Current.File.Url

1
这段代码适用于位于 _layouts 目录下的页面以及站点中的“普通”页面:
        string thisPageUrl;
        if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("_layouts"))
        {
            thisPageUrl = SPContext.Current.Web.Url + context.Request.Path; //note: cannot rely on Request.Url to be correct !
        }
        else
        {
            thisPageUrl = HttpContext.Current.Request.Url.ToString();
        }

这将排除可能的查询字符串。 - Oleg Savelyev

1

这应该返回您需要的内容:SPContext.Current.ListItemServerRelativeUrl


1
我使用了一个解决方法,可以覆盖_layouts的情况。
/// <summary>
/// Builds real URL considering layouts pages.
/// </summary>
private Uri CurrentUrl
{
    get
    {
        return Request.Url.ToString().ToLower().Contains("_layouts")
            ? new Uri(
                SPContext.Current.Site.WebApplication.GetResponseUri(
                    SPContext.Current.Site.Zone).ToString().TrimEnd('/')
                + Request.RawUrl) 
            : Request.Url;
    }
}

0
 string filename = Path.GetFileName(Request.Path);

-1
string PageTitle=SPContext.Current.File.Title

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接