HttpListener 应用程序在处理第一个请求后关闭

问题描述 投票:0回答:1
await main.RunWebHookSubscription();
//

public async Task RunWebHookSubscription()
        {

            Console.WriteLine("Hook waiting");

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/hook/");
            listener.Start();
            Task<HttpListenerContext> context = listener.GetContextAsync();
            await HandleRequestAsyncRun(await context);
        }

        async Task HandleRequestAsyncRun(HttpListenerContext context)
        {
            var request = context.Request;
            var body = WebHookRequestHadler(request);
            Console.Write(body);
            var eventData = JsonSerializer.Deserialize<WebHookEventData>(body);
            //TODO Call method
        }

        string WebHookRequestHadler(HttpListenerRequest request)
        {
            
            if (!request.HasEntityBody)
            {
                return null;
            }
            using (System.IO.Stream body = request.InputStream) // here we have data
            {
                using (var reader = new System.IO.StreamReader(body, request.ContentEncoding))
                {
                    return reader.ReadToEnd();
                }
            }

处理完第一个请求后,我的应用程序关闭了。我怎样才能永久处理请求?

c# .net .net-core httplistener
1个回答
1
投票

您需要将上下文交给另一个线程,然后循环返回以接受另一个连接。

你还应该用

using
处理上下文,并在
finally
中停止听众。

public async Task RunWebHookSubscription()
{
    Console.WriteLine("Hook waiting");

    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:8080/hook/");
    listener.Start();
    try
    {
        while (true)
        {
            context = await listener.GetContextAsync();
            Task.Run(async () =>
            {
                using (context)
                    await HandleRequestAsyncRun(context);
            });
        }
    }
    finally
    {
        listener.Stop();
    }
}

考虑使用

Console.CancelKeyPress
CancellationTokenSource
来取消监听器循环。

© www.soinside.com 2019 - 2024. All rights reserved.