Path.Combine for URLs?

前端 未结 30 2432
不思量自难忘°
不思量自难忘° 2020-11-22 14:28

Path.Combine is handy, but is there a similar function in the .NET framework for URLs?

I\'m looking for syntax like this:

Url.Combine(\"http://MyUrl.         


        
30条回答
  •  悲&欢浪女
    2020-11-22 15:14

    If you don't want to add a third-party dependency such as Flurl or create a custom extension method, in ASP.NET Core (also available in Microsoft.Owin), you can use PathString which is intended for the purpose of building up URI paths. You can then create your full URI using a combination of this, Uri and UriBuilder.

    In this case, it would be:

    new Uri(new UriBuilder("http", "MyUrl.com").Uri, new PathString("/Images").Add("/Image.jpg").ToString())
    

    This gives you all the constituent parts without having to specify the separators in the base URL. Unfortunately, PathString requires that / is prepended to each string otherwise it in fact throws an ArgumentException! But at least you can build up your URI deterministically in a way that is easily unit-testable.

提交回复
热议问题