如果您可以使用控制器/动作名称...
您应该为此使用Url.Action() 方法。
通常情况下,Url.Action() 将返回类似于您目前所期望的仅提供控制器和操作名称的内容:
// This would yield "Controller/Action"
Url.Action("Action","Controller");
但是,当您传入协议参数(即http、https 等)时,该方法实际上将返回一个完整的绝对 URL。为方便起见,您可以使用Request.Url.Scheme 属性访问相应的协议,如下所示:
// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);
你可以see an example of this in action here。
如果您只有一个相对 URL 字符串...
如果您只能访问相对 URL(即 ~/controller/action),那么您可能需要创建一个函数来扩展 Url.Content() 方法的当前功能以支持提供绝对 URL:
public static class UrlExtensions
{
public static string AbsoluteContent(this UrlHelper urlHelper, string contentPath)
{
// Build a URI for the requested path
var url = new Uri(HttpContext.Current.Request.Url, urlHelper.Content(contentPath));
// Return the absolute UrI
return url.AbsoluteUri;
}
}
如果定义正确,这将允许您简单地将您的 Url.Content() 调用替换为 Url.AbsoluteContent(),如下所示:
Url.AbsoluteContent("~/Controller/Action")
你可以see an example of this approach here。