本日はC#の小ネタ枠です。
HttpListenerを使ってリダイレクトURLを受け取る方法についです。
HttpListener.GetContextAsync
HttpListener.GetContextAsyncは非同期でHttp通信の受信要求を待機します。
本関数の実行前にHttpListenerに受信待機するURLプレフィックスをPrefix変数に指定する必要があります。
learn.microsoft.com
HttpListener httpListener = new HttpListener(); httpListener.Prefixes.Add(redirectUri); httpListener.Start(); var context = await httpListener.GetContextAsync();
サンプルコード
UniRxを取り込んだUnity環境でリダイレクトURLを受け取って、そこに含まれるパラメータをレスポンスページに表示する以下のサンプルコードを作成しました。
・RedirectURLTest.cs
using System; using System.Net; using System.Text; using System.Web; using Cysharp.Threading.Tasks; using UniRx; using UnityEngine; using UnityEngine.UI; public class RedirectURLTest : MonoBehaviour { [SerializeField] private Button button; private HttpListener httpListener; public void Start() { string redirectUri = "http://127.0.0.1/"; // HTTPサーバを立ててリダイレクトURLを受け取る httpListener = new HttpListener(); httpListener.Prefixes.Add(redirectUri); httpListener.Start(); UniTask.Create(async () => { try { var context = await httpListener.GetContextAsync(); var response = context.Response; // 受け取ったリダイレクトURLをログに出力する Debug.Log($"redirectUri: {context.Request.Url}"); // 受け取ったリダイレクトURLのクエリパラメータからcodeを取得する var query = context.Request.Url.Query; var code = HttpUtility.ParseQueryString(query).Get("code"); // リダイレクトURLで開くページのレスポンスページに取得したcodeを表示する var responseString = $"<html><body>Get code : {code}</body></html>"; var buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; await responseOutput.WriteAsync(buffer, 0, buffer.Length); responseOutput.Close(); httpListener?.Stop(); } catch (ObjectDisposedException ex) { return; } }).Forget(); button.OnClickAsObservable() // ボタン押下時にリダイレクトURLを開く .Subscribe(_ => UnityEngine.Application.OpenURL(redirectUri + "?code=1234567890")) .AddTo(this); } void Destroy() { httpListener?.Stop(); } }
シーンを再生して参照を設定したボタンを押下すると以下のURLが開きます。
http://127.0.0.1/?code=1234567890
HttpListenerがURLを受信し、パラメータを記載したレスポンスページが開きました。