I have a simple .net core web api with one action:
[Route("[action]")]
public class APIController : Controller
{
// GET api/values
[HttpGet]
public string Ping()
{
return DateTime.Now.ToString();
}
}
If I run this via dotnet run I get
Hosting environment: Production
Content root path: C:\Users\xxx\Documents\Visual Studio 2015\Projects\SelfHostTest\src\SelfHostTest
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Going to the browser and typing in http://localhost:5000/ping results in a successful return of the current time. However going to a remote machine (same LAN) and trying to access the service via http://odin:5000/ping results in a 404 error. (Odin is the name of the machine running the web api in a console via dotnet run).
Both server (and client!) firewalls are turned off. I can ping "odin" successfully.
Any ideas what simple step I am missing here. I've tried this at home and at work with no success.
ASP.NET Web API does not require IIS. You can self-host a web API in your own host process. New applications should use OWIN to self-host Web API. See Use OWIN to Self-Host ASP.NET Web API 2.
ASP.NET Core supports creating web APIs using controllers or using minimal APIs. Controllers in a web API are classes that derive from ControllerBase. This article shows how to use controllers for handling web API requests.
My guess is that the issue isn't in your controller, it is in program.cs. You need to modify the construction of your WebHost
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://localhost:5000", "http://odin:5000", "http://192.168.1.2:5000")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
Unless you add the UseUrls line, Kestrel isn't going to listen outside of localhost. This makes sense, because in a normal situation Kestrel will be sitting behind a reverse proxy like IIS or NGNIX and doesn't need to bind to external URLs.
The best way is to adjust the launchSettings.json
, which is located inside the Properties
folder.
Change
"applicationUrl": "https://localhost:5001"
to
"applicationUrl": "https://0.0.0.0:5001"
This allows the Kestrel Web Server to listen for traffic from all Network Interfaces.
You can simply do the following to create your WebHost, this will allow remote connections to kestrel.
var host = WebHost.CreateDefaultBuilder(args)
.UseUrls("http://0.0.0.0:80")
.UseStartup<Startup>()
.Build();
After using the following code I still wasn't able to access my API remotely, I had to disable the network adapters created by Docker in the windows control panel (Control Panel\Network and Internet\Network Connections)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With