Search code examples
c#visual-studio-2019httplistenerwindows-server-2019

Call HttpListener from external IP


I have a very simple API in C# for test purposes. The API is created in a Windows Forms project

listener = new HttpListener();               
listener.Prefixes.Add(url);
listener.Start();
LogUtils.appendInfo("Listening for connections on: " + url);
//Handle requests
Task listenTask = HandleIncomingConnections();
listenTask.GetAwaiter().GetResult();

If I call http://localhost:8080/ I get response from API.

The problem is that if I call the API from another PC using the external IP address http://ExternalIp:8080/

I get this error:

Bad Request - Invalid Hostname HTTP Error 400. The request hostname is invalid

What I have tried:

  • I have put in the firewall a rule for port 8080 in incoming connections.
  • I have tested with the ISS server that brings Windows Server 2019 off and on.
  • I have created a 'applicationhost.config 'file in 'C:\Users\myUser\source\repos\myProyect.vs\proyectname\config' for <'binding protocol="http" bindingInformation=":8080:" /> because my project not have applicationhost.config file.

Solution

  • As @PanagiotisKanavos commented I can not use "localhost" in "listener.Prefixes.Add" for external request.

    Solved by:

    http://*:8080/
    

    And run Visual Studio as administrator.