uwp httplistener not listening

115 views Asked by At

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.

1

There are 1 answers

2
Roy Li - MSFT On

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.