3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】URLのリダイレクト先を取得する

Last updated at Posted at 2019-03-16

C#におけるURLを用いた処理では、リダイレクト先を内部的に取得して処理してくれます。
内部的に取得されたリダイレクト先URLを取り出したかったのですが、少しハマったので備忘録程度に記事にしました。

やりたいこと

URLを投げたら最終的なリダイレクト先のURLを返して欲しい

コード

using
using System.Diagnostics;
using System.Threading.Tasks;
using System.Net.Http;
ロジック
static void Main(string[] args)
{
	//リダイレクト先を知りたいURL
	string url = "https://goo.gl/xBVejN";

	//リダイレクト先の取得が終わるまで待つ
	Task<string> task = GetLastUrl(url);
	task.Wait();

	//リダイレクト先を表示
	Debug.WriteLine("リダイレクト先 : " + task.Result);
}
		
//リダイレクト先の取得
public static async Task<string> GetLastUrl(string url)
{
	HttpClient client = new HttpClient();
	HttpResponseMessage response = await client.GetAsync(url);
	response.EnsureSuccessStatusCode();

	return response.RequestMessage.RequestUri.ToString();
}
実行結果
リダイレクト先 : https://wikiwiki.jp/kancolle/北上

上のソースでは、短縮URL化した艦これ攻略Wiki北上様のURLを与えてみましたが、正しく結果を得られました。
HttpResponseMessageクラスRequestUriプロパティには、リダイレクト先のURL(URI)が格納されていますので、それを読みに行くだけのシンプルな構造です。
必要であれば例外処理を追加することで柔軟な処理が可能になります。

参考

HttpClient Class
https://docs.microsoft.com/ja-jp/dotnet/api/system.net.http.httpclient

HttpRequestMessage.RequestUri Property
https://docs.microsoft.com/ja-jp/dotnet/api/system.net.http.httprequestmessage.requesturi

C# 今更ですが、HttpClientを使う
https://qiita.com/rawr/items/f78a3830d894042f891b

Google URL Shortener
https://goo.gl/

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?