Path.Combine很方便,但是.NET框架中是否有类似的URL函数?
我正在寻找这样的语法:
Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
这将返回:
"http://MyUrl.com/Images/Image.jpg"
Path.Combine很方便,但是.NET框架中是否有类似的URL函数?
我正在寻找这样的语法:
Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
这将返回:
"http://MyUrl.com/Images/Image.jpg"
当前回答
上面有托德·梅尼尔(Todd Menier)的评论,Flurl包括一个Url.Combine。
更多详情:
Url.Combine基本上是Url的Path.Combine,确保部分之间只有一个分隔符:
var url = Url.Combine(
"http://MyUrl.com/",
"/too/", "/many/", "/slashes/",
"too", "few?",
"x=1", "y=2"
// result: "http://www.MyUrl.com/too/many/slashes/too/few?x=1&y=2"
在NuGet上获取Flurl.Http:
PM>安装包Flurl.Http
或者获取没有HTTP功能的独立URL生成器:
PM>安装程序包Flurl
其他回答
我使用此代码来解决问题:
string[] brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
string[] brokenRootFolderPath = RootFolderPath.Split('/');
for (int x = 0; x < brokenRootFolderPath.Length; x++)
{
//if url doesn't already contain member, append it to the end of the string with / in front
if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
{
if (x == 0)
{
RootLocationUrl = Context.Url.TrimEnd('/');
}
else
{
RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
}
}
}
您使用Uri.TryCreate(…):
Uri result = null;
if (Uri.TryCreate(new Uri("http://msdn.microsoft.com/en-us/library/"), "/en-us/library/system.uri.trycreate.aspx", out result))
{
Console.WriteLine(result);
}
将返回:
http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx
如果任何人正在寻找一个单行,并且只想在不创建新方法或引用新库的情况下连接路径的一部分,或者构造URI值并将其转换为字符串,那么。。。
string urlToImage = String.Join("/", "websiteUrl", "folder1", "folder2", "folder3", "item");
这很基本,但我看不出你还需要什么。如果你害怕“/”加倍,那么你可以简单地在后面做一个替换(“//”,“/”)。如果您害怕替换“https://”中的双引号“//”,那么请执行一次连接,替换双引号“/”,然后加入网站url(但是我很确定大多数浏览器会自动将前面带有“https://的内容转换为正确格式)。这看起来像:
string urlToImage = String.Join("/","websiteUrl", String.Join("/", "folder1", "folder2", "folder3", "item").Replace("//","/"));
这里有很多答案可以解决以上所有问题,但在我的情况下,我只需要在一个地方使用一次,不需要过度依赖它。此外,很容易看到这里发生了什么。
参见:https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8
Uri有一个构造函数可以为您执行此操作:new Uri(Uri baseUri,string relativeUri)
下面是一个示例:
Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
编辑注意:小心,这种方法并不能像预期的那样工作。在某些情况下,它可以剪切baseUri的一部分。查看评论和其他答案。
有趣的例子,Ryan,以函数的链接结尾。做得好。
一个建议Brian:如果您将此代码包装在函数中,则可能需要在TryCreate调用之前使用UriBuilder包装基URL。
否则,基本URL必须包含方案(其中UriBuilder将采用http://)。只是一个想法:
public string CombineUrl(string baseUrl, string relativeUrl) {
UriBuilder baseUri = new UriBuilder(baseUrl);
Uri newUri;
if (Uri.TryCreate(baseUri.Uri, relativeUrl, out newUri))
return newUri.ToString();
else
throw new ArgumentException("Unable to combine specified url values");
}