0

I have a ToggleSwitch that launches a HttpListener when it is turned on. Below is the code that turns the listener on.

My problem is that the HttpListener is not listening. I requested http://localhost:8023 via Postman and the request is always timed out. And the GetContextCallBack is only called when httpListener.Stop() is invoked. What's the problem of my code? It works in a console app but does not work in UWP.

private void LaunchLocalServer(int port)
{
    httpListener = new HttpListener();
    httpListener.Prefixes.Add($"http://127.0.0.1:{port}/");
    httpListener.Start();
    httpListener.BeginGetContext(new AsyncCallback(GetContextCallBack), httpListener);
}

private void GetContextCallBack(IAsyncResult ar)
{
    try
    {
        HttpListener _listener = ar.AsyncState as HttpListener;
        if (_listener.IsListening)
        {
            return;
        }

        HttpListenerContext context = _listener.EndGetContext(ar);
        _listener.BeginGetContext(new AsyncCallback(GetContextCallBack), _listener);

        HttpListenerResponse response = context.Response;
        response.StatusCode = (int)HttpStatusCode.OK;
        response.ContentType = "application/json;charset=UTF-8";
        response.ContentEncoding = Encoding.UTF8;
        response.AppendHeader("Content-Type", "application/json;charset=UTF-8");

        var abcOject = new
        {
            code = "200",
            description = "success",
            data = "time=" + DateTime.Now
        };
        string responseString = JsonConvert.SerializeObject(abcOject,
            new JsonSerializerSettings()
            {
                StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
            });

        using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
        {
            writer.Write(responseString);
            writer.Close();
            response.Close();
        }
    }
    catch (Exception ex)
    {
        Log.Warn($"handle response failed {ex}");
    }
}

Full code is here.

Seaky Lone
  • 992
  • 1
  • 10
  • 29
  • Is Windows Firewall blocking it? What do you see in `tcpview`? – Dai Nov 06 '22 at 11:37
  • Also, why are you using the _old_ `BeginGetContext` method instead of the _newer and better_ `GetContextAsync` method? – Dai Nov 06 '22 at 11:37
  • I don't think Windows Firewall is blocking it. This piece of code works in a console app but does not work in UWP. – Seaky Lone Nov 06 '22 at 12:11
  • @Dai I googled `HttpListener` and the code demo I got all about `BeginGetContext`, so I used it. I just tried `GetContextAsync`, it was still the same result. The listener only execute the code after `GetContextAsync` when the listener is stopped. – Seaky Lone Nov 06 '22 at 12:22

1 Answers1

0

A general reason for this behavior is that you will need to enable the local loopback for the UWP app first- UWP Enable local network loopback. UWP apps are running in the sandbox and are isolated from the system resources. Enabling the local network loopback could make UWP apps possible to access local network resources.

Roy Li - MSFT
  • 8,043
  • 1
  • 7
  • 13
  • Hi, I have tried `checknetisolation loopbackexempt -a -n=` and `checknetisolation loopbackexempt -c`. Both operations were executed but did nothing. I have also referred to the [link][https://learn.microsoft.com/en-us/windows/uwp/communication/interprocess-communication] and added capability of `privateNetworkClientServer` to my app, and I still couldn't connect to the local server port. Could you please check my code and see what I am missing? – Seaky Lone Nov 08 '22 at 14:47
  • @SeakyLone Please make sure that you are using the correct package family name not the package name. – Roy Li - MSFT Nov 25 '22 at 03:24