Since your configuration class information is incomplete, I made a simple demo here, you can refer to the following:
1.First create a new RegisterConsul extension method:
public static class AppBuilderExtensions
{
public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ServiceEntity serviceEntity)
{
var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//Consul address requesting registration
var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//How long does it take to register after the service starts
Interval = TimeSpan.FromSeconds(10),//Health check interval, or heartbeat interval
HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/WeatherForecast",//Health check address
Timeout = TimeSpan.FromSeconds(5)
};
// Register service with consul
var registration = new AgentServiceRegistration()
{
Checks = new[] { httpCheck },
ID = Guid.NewGuid().ToString(),
Name = serviceEntity.ServiceName,
Address = serviceEntity.IP,
Port = serviceEntity.Port,
Tags = new[] { $"urlprefix-/{serviceEntity.ServiceName}" }//Add a tag tag in the format of urlprefix-/servicename so that Fabio can recognize it
};
consulClient.Agent.ServiceRegister(registration).Wait();//Register when the service starts, the internal implementation is actually to register using the Consul API (initiated by HttpClient)
lifetime.ApplicationStopping.Register(() =>
{
consulClient.Agent.ServiceDeregister(registration.ID).Wait();//Unregister when the service stops
});
return app;
}
}
2.ServiceEntity Model:
public string IP { get; set; }
public int Port { get; set; }
public string ServiceName { get; set; }
public string ConsulIP { get; set; }
public int ConsulPort { get; set; }
3.Add the following configuration to the configuration file, here is added to appSetting.json
"Consul": {
"IP": "localhost",
"Port": 44326,
"ServiceName": "hotel_api",
"ConsulIP": "Your consul address ",
"ConsulPort": Your consul port number
}
4.Then add in the Configure method in the Startup class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.Extensions.Hosting.IHostApplicationLifetime lifetime)
{
ServiceEntity serviceEntity = new ServiceEntity
{
IP = "localhost",
Port = Convert.ToInt32(Configuration["Consul:Port"]),
ServiceName = Configuration["Consul:ServiceName"],
ConsulIP = Configuration["Consul:ConsulIP"],
ConsulPort = Convert.ToInt32(Configuration["Consul:ConsulPort"])
};
app.RegisterConsul(lifetime, serviceEntity);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
5.Result:
