在網頁使用相對網址,瀏覽器會自動幫忙轉成絕對網址,如果是在 C# 程式寫程式推算,該怎麼寫?

一開始我又用傳統思維開始想演算法,先轉成 Uri 物件解析出 Host、PathAndQuery 再算位置弄半天,後來發現自己耍笨了,Uri 建構式已直接支援

public Uri (Uri baseUri, string? relativeUri);

紀念白忙一場,寫範例驗證兼筆記:

void Main()
{
	var tests = new List<string>() {
		"https://store.darkthread.net/shopping/cart",
		"https://store.darkthread.net/shopping/cart/",
		"https://store.darkthread.net/shopping/cart/view",
		"https://store.darkthread.net/shopping/cart/view?f=24h",
		"https://store.darkthread.net/shopping/cart/view.aspx?f=24h"
	};
	
	Action<string> test = (relUrl) => 
	{
		Console.WriteLine($"Testing [{relUrl}] ...");	
		tests.ForEach(baseUrl => {
			var u = new Uri(new Uri(baseUrl), relUrl);
			Console.WriteLine(u.ToString());
		});
	};
	
	test("../help/contact");
	test(".");
	test("..");
	test("?sort=prz#summary");
}

同場加映,如果是絕對轉相對怎麼辦?public Uri MakeRelativeUri (Uri uri); 以前計算檔案路徑時用過,用在網址當然沒問題。

關於 Uri 各部分解析,推薦保哥的這篇:講解 URL 結構與分享幾個相對路徑與絕對路徑的開發技巧,你可能會有一些新發現。

Tips of how to resolve relative URL to absolute URL with .NET.


Comments

# by ByTim

幫補充:Mvc的UrlHelper,有各種URL函式

Post a comment