LoginSignup
12
14

More than 5 years have passed since last update.

C# LINQPadでお手軽Webサーバ

Last updated at Posted at 2017-04-21

なんとなくWebリクエストを投げたくなったとき、壊してもよいWebサーバがあるととても便利。

HTTPレスポンスを好きなように生成したり、遅延をシミュレートしたりもできるWebサーバをさっくり立ててみる。
立てたサーバには http://localhost:9999/test などのURLで接続できる。

System.Net
System.Threading.Tasks
void Main()
{
    CancellationTokenSource cts = new CancellationTokenSource();
    var t = StartListener(cts.Token);

    Console.WriteLine("Press enter to stop.");
    Console.ReadLine();

    cts.Cancel();
    try
    {
        t.Wait();
    }
    catch {}
}

async Task StartListener(CancellationToken ct)
{
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:9999/");
    listener.Start();
    ct.Register(()=>listener.Stop());

    while (!ct.IsCancellationRequested)
    {
        var context = await listener.GetContextAsync();
        var req = context.Request;
        var res = context.Response;

        Debug.WriteLine("Connected From: " + req.RemoteEndPoint);
        await Task.Delay(500);

        var response = $"{req.HttpMethod} {req.RawUrl} HTTP/{req.ProtocolVersion}\r\n";
        response += String.Join("\r\n", req.Headers.AllKeys.Select(k => $"{k}: {req.Headers[k]}"));

        var responsedata = Encoding.ASCII.GetBytes(response);
        res.OutputStream.Write(responsedata, 0, responsedata.Length);
        res.Close();
    }
}

※Visual Studio でもできるけど LINQPad の手軽さが大事。

12
14
0

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
12
14