Я думал, что я разделю свой подход к выполнению этого в ASP.NET MVC с помощью Uri
класса и некоторое расширение магии.
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
}
Вы можете затем вывести абсолютный путь, используя:
// gives absolute path, e.g. https://example.com/customers
Url.AbsolutePath(Url.Action("Index", "Customers"));
Это выглядит немного некрасиво, имеющий вложенные вызовы методов, так что я предпочитаю, чтобы в дальнейшем расширить UrlHelper
с обычными способами действий, так что я могу сделать:
// gives absolute path, e.g. https://example.com/customers
Url.AbsoluteAction("Index", "Customers");
или
Url.AbsoluteAction("Details", "Customers", new{id = 123});
Полный класс расширения выглядит следующим образом:
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
public static string AbsoluteAction(this UrlHelper urlHelper,
string actionName,
string controllerName)
{
return AbsolutePath(urlHelper,
urlHelper.Action(actionName, controllerName));
}
public static string AbsoluteAction(this UrlHelper urlHelper,
string actionName,
string controllerName,
object routeValues)
{
return AbsolutePath(urlHelper,
urlHelper.Action(actionName,
controllerName, routeValues));
}
}
2 связанных ответы по адресу: // StackOverflow .com/вопросы/7413466/how-can-i-get-the-baseurl-of-site и http://stackoverflow.com/questions/3933662/in-asp-net-what-is-the-quickest-way -to-get-the-base-url-for-a-request – 2013-07-10 19:41:16