tyinde
tyinde

Reputation: 5

How to change localhost to local ip for a .NET 7 web application?

I've built a small web application using .NET 7. It works fine locally with https://127.0.0.1:1234 or https://localhost:1234.

It uses the GET/POST API calls to get data from other computers and send to a database. So I want it able to be connect by other devices in the same network. When i change it with my real local IP, like https://192.168.1.1:9111, it doesn't work anymore. I'm getting

Error: socket hang up

from Postman.

Here is my code. Did I miss anything?

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.Run("https://192.168.1.1:9111");
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Upvotes: 0

Views: 772

Answers (2)

Louis
Louis

Reputation: 26

You need to specify which endpoints your API should listen on.

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:9111", "http://127.0.0.1:9111", "http://192.168.1.1:9111");
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();

// Rest of your code
// You do not need the `app.Run...` part

Upvotes: 1

fako
fako

Reputation: 38

If you want able to be connect by other devices, You need to install IIS on your computer or any other server technology and just run

app.Run();

Upvotes: 0

Related Questions