在网站启动和卸载的时候添加对应注册和卸载事件
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserContext>(options =>
{
options.UseMySQL(Configuration.GetConnectionString("MysqlUser"));
});
//从配置文件中获取ServiceDiscovery
services.Configure<ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery"));
//单例注册ConsulClient
services.AddSingleton<IConsulClient>(p => new ConsulClient(cfg =>
{
var serviceConfiguration = p.GetRequiredService<IOptions<ServiceDisvoveryOptions>>().Value;
if (!string.IsNullOrEmpty(serviceConfiguration.Consul.HttpEndpoint))
{
// if not configured, the client will use the default value "127.0.0.1:8500"
cfg.Address = new Uri(serviceConfiguration.Consul.HttpEndpoint);
}
}));
services.AddMvc();
//添加授权相关代码
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect(//配置授权信息相关
"oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:52619";//授权地址
options.RequireHttpsMetadata = false;//ssl证书
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
options.ClientId = "MVC";
options.ClientSecret = "Secret";
options.SaveTokens = true;
// options.GetClaimsFromUserInfoEndpoint = true;//发起另外一个请求~52619/content/userInfo 获取userinfo
//options.ClaimActions.MapJsonKey("sub", "sub");
//options.ClaimActions.MapJsonKey("preferred_username", "preferred_username");
//options.ClaimActions.MapJsonKey("sub", "sub");
//options.ClaimActions.MapJsonKey("avatar", "avatar");
//options.ClaimActions.MapCustomJson("role", jobject => jobject["role"].ToString());
options.Scope.Add("geteway_api");
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
//options.Scope.Add("email");
}
);//添加
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory LoggerFactory,
IApplicationLifetime lifetime,
IConsulClient consulClient,
IOptions<ServiceDisvoveryOptions> DisvoveryOptions)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseAuthentication();
lifetime.ApplicationStarted.Register(() =>
{
RegisterService(app, DisvoveryOptions, consulClient);
});
lifetime.ApplicationStopped.Register(() =>
{
DeRegisterService(app, DisvoveryOptions, consulClient);
});
UserContextSeed.SeedAsync(app, LoggerFactory).Wait();
//InitUserDataBase(app);//初始化数据库脚本再创建数据库之后取消注释
}
//注册服务方法
private void RegisterService(IApplicationBuilder app,
IOptions<ServiceDisvoveryOptions> serviceOptions,
IConsulClient consul)
{
//从当前启动的url中拿到url
var features = app.Properties["server.Features"] as FeatureCollection;
var addresses = features.Get<IServerAddressesFeature>()
.Addresses
.Select(p => new Uri(p));
foreach (var address in addresses)
{
var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}";
var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1),
Interval = TimeSpan.FromSeconds(30),
HTTP = new Uri(address, "HealthCheck").OriginalString
};
var registration = new AgentServiceRegistration()
{
Checks = new[] { httpCheck },
Address = address.Host,
ID = serviceId,
Name = serviceOptions.Value.ServiceName,
Port = address.Port
};
consul.Agent.ServiceRegister(registration).GetAwaiter().GetResult();
}
}
//移除方法
private void DeRegisterService(IApplicationBuilder app,
IOptions<ServiceDisvoveryOptions> serviceOptions,
IConsulClient consul)
{
//从当前启动的url中拿到url
var features = app.Properties["server.Features"] as FeatureCollection;
var addresses = features.Get<IServerAddressesFeature>()
.Addresses
.Select(p => new Uri(p));
foreach (var address in addresses)
{
var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}";
consul.Agent.ServiceDeregister(serviceId).GetAwaiter().GetResult();
}
}
}