gpt4 book ai didi

c# - 从相对路径获取绝对URL(重构方法)

转载 作者:IT王子 更新时间:2023-10-29 03:47:06 26 4
gpt4 key购买 nike

令我感到非常惊讶的是,没有 native .NET 方法可以从相对 URL 获取绝对 URL。我知道这已经被讨论过很多次,但从来没有遇到过一个令人满意的方法来很好地处理这个问题。你能帮忙微调下面的方法吗?

我想我只需要自动选择协议(protocol)而不是对其进行硬编码 (http/https)。我还有什么遗漏的吗(注意事项、性能等)?

public static string GetAbsoluteUrl(string url)
{
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return url;
}

//GET PAGE REFERENCE FOR CONTEXT PROCESSING
Page page = HttpContext.Current.Handler as Page;

//RESOLVE PATH FOR APPLICATION BEFORE PROCESSING
if (url.StartsWith("~/"))
{
url = page.ResolveUrl(url);
}

//BUILD AND RETURN ABSOLUTE URL
return "http://" + page.Request.ServerVariables["SERVER_NAME"] + "/"
+ url.TrimStart('/');
}

最佳答案

这一直是我处理这个小麻烦的方法。注意 VirtualPathUtility.ToAbsolute(relativeUrl) 的使用允许将方法声明为静态类中的扩展。

/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;

if (HttpContext.Current == null)
return relativeUrl;

if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");

var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}

关于c# - 从相对路径获取绝对URL(重构方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3681052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com