tôi nghĩ rằng tôi muốn chia sẻ cách tiếp cận của tôi để làm điều này trong ASP.NET MVC sử dụng lớp Uri
và một số ma thuật mở rộng.
public static class UrlHelperExtensions
{
public static string AbsolutePath(this UrlHelper urlHelper,
string relativePath)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
relativePath).ToString();
}
}
Bạn có thể sau đó đầu ra một đường dẫn tuyệt đối sử dụng:
// gives absolute path, e.g. https://example.com/customers
Url.AbsolutePath(Url.Action("Index", "Customers"));
Có vẻ một chút xấu xí có phương pháp lồng nhau gọi vì vậy tôi thích để mở rộng hơn nữa UrlHelper
với các phương pháp hành động chung vì vậy mà tôi có thể làm:
// gives absolute path, e.g. https://example.com/customers
Url.AbsoluteAction("Index", "Customers");
hoặc
Url.AbsoluteAction("Details", "Customers", new{id = 123});
.210
Lớp mở rộng đầy đủ như sau:
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 câu trả lời liên quan tại địa chỉ: http: // stackoverflow .com/questions/7413466/how-can-i-get-the-baseurl-of-site và http://stackoverflow.com/questions/3933662/in-asp-net-what-is-the-quickest-way -to-get-the-base-url-cho-một-yêu cầu –