3

I prepared WinForms App and migrate it to .NET 6, and then follow answer from this question: Hosting ASP.NET Core API in a Windows Forms Application

How I will change app to allow connect to api from devices in LAN network?

i tried something like this:

var host = CreateWebHostBuilder(args)
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://localhost:5000", "http://aError:5000", "http://0.0.0.0:6000")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

But i can still from my PC connect to local host, aError not working.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

1 Answers1

2

Ok the solution that I found is:

string localIP = LocalIPAddress();

var host = CreateWebHostBuilder(args)
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://localhost:5000", $"http://{localIP}:5000")
    .UseIISIntegration()
    .UseStartup<Startup>()              
    .Build();


static string LocalIPAddress()
{
    using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
    {
        socket.Connect("8.8.8.8", 65530);
        IPEndPoint? endPoint = socket.LocalEndPoint as IPEndPoint;
        if (endPoint != null)
        {
            return endPoint.Address.ToString();
        }
        else
        {
            return "127.0.0.1";
        }
    }
}

And on IP from this static method, I can access API from all devices in lan ;)

Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36