2

【笨問題】C# 相對網址與絕對網址轉換

 3 years ago
source link: https://blog.darkthread.net/blog/resolve-relative-url-w-csharp/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【笨問題】C# 相對網址與絕對網址轉換

calendar.svg 2021-06-15 08:40 PM comment.svg 1 eye.svg 1,130

在網頁使用相對網址,瀏覽器會自動幫忙轉成絕對網址,如果是在 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 結構與分享幾個相對路徑與絕對路徑的開發技巧,你可能會有一些新發現。

  • Posted in
  • C#
and has 1 comment

Comments

Post a comment

Comment
Name Captcha 94 - 38 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK