How to get current page URL in MVC 3

2019-01-03 21:31发布

I am using the Facebook comments plugin on a blog I am building. It has some FBXML tags that are interpreted by the facebook javascript that is referenced on the page.

This all works fine, but I have to pass in the current, fully-qualified URL to the plugin.

<div style="width: 900px; margin: auto;">
    <div id="fb-root"></div>
    <fb:comments href="URL HERE" num_posts="10" width="900"></fb:comments>
</div>

What is the best way to get the URL of the current page? The request URL.

Solution

Here is the final code of my solution:

<fb:comments href="@Request.Url.AbsoluteUri" num_posts="15" width="900"></fb:comments>

8条回答
我命由我不由天
2楼-- · 2019-01-03 21:55

For me the issue was when I tried to access HTTPContext in the Controller's constructor while HTTPContext is not ready yet. When moved inside Index method it worked:

var uri = new Uri(Request.Url.AbsoluteUri);
url = uri.Scheme + "://" + uri.Host + "/";enter code here
查看更多
孤傲高冷的网名
3楼-- · 2019-01-03 21:58
public static string GetCurrentWebsiteRoot()
{
    return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
}
查看更多
登录 后发表回答