/// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/systemmanage/swagger.json", "My API V1"); }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); ConsulHelper.RegisterService($"http://{LocalInfo.SlbIp}:8500", "dc1", "systemmanage", LocalInfo.ServerIp, 6020).Wait(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); Settings.AuthorizationKey = Configuration.GetSection("ApplicationSettings:AuthorizationKey")?.Value; // Add Application Insights services into service collection services.AddApplicationInsightsTelemetry(); // Add the standard telemetry client services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>(); // Add ASP middleware to store the HTTP body, mapped with bot activity key, in the httpcontext.items // This will be picked by the TelemetryBotIdInitializer services.AddTransient <TelemetrySaveBodyASPMiddleware>(); // Add telemetry initializer that will set the correlation context for all telemetry items services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>(); // Add telemetry initializer that sets the user ID and session ID (in addition to other // bot-specific properties, such as activity ID) services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>(); // Create the telemetry middleware to track conversation events services.AddSingleton <IMiddleware, TelemetryLoggerMiddleware>(); var apps = new List <LuisAppRegistration>(); Configuration.GetSection("LuisAppRegistrations").Bind(apps); Settings.LuisAppRegistrations = apps; // Adding Consul hosted service using (ConsulHelper consulHelper = new ConsulHelper(EnvironmentName, ContentRootPath)) { consulHelper.Initialize(services, Configuration); } services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "https://BotApp.Luis.Router.Identity", ValidAudience = "https://BotApp.Luis.Router.Identity", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.AuthorizationKey)) }; }); services.AddCors(o => o.AddPolicy("AllowAllPolicy", options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); }
private async void OnApplicationStopping() { using (ConsulHelper consulHelper = new ConsulHelper(EnvironmentName, ContentRootPath)) { await consulHelper.Stop(); } }
private async Task <int> ExecuteAsync(Uri address, string token, bool all) { using var client = ConsulHelper.CreateConsulClient(address, token); Console.WriteLine($"Diff started. Address: {client.Config?.Address}"); return(await CompareFiles(client, includeIdenticalResults : all)); }
private async Task <int> ExecuteAsync(Uri address, string token, string file) { using var client = ConsulHelper.CreateConsulClient(address, token); Console.WriteLine($"Diff started. Address: {client.Config?.Address}"); try { var pair = await client.KV.Get(file); if (pair?.Response == null) { await Console.Error.WriteLineAsync($"Cannot find key on consul: {file}"); return(1); } return(await CompareFileContents(pair.Response)); } catch (Exception ex) { await Console.Error.WriteLineAsync($"Cannot compare file: {ex.Message}"); return(1); } }
public void Configure(IApplicationBuilder app, ILogger <Startup> logger) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); }); var ip = Configuration["ip"]; var port = Convert.ToInt32(Configuration["port"]); try { var result = ConsulHelper.ServiceRegister(logger, ip, port).Result; if (result.StatusCode != HttpStatusCode.OK) { logger.LogError("注册服务失败。Result:{@result}", result); } else { logger.LogInformation("注册服务成功。Result:{@result}", result); } } catch (Exception ex) { logger.LogError(ex, "注册服务发生错误。"); } }
/// <summary> /// Consul处理器 /// </summary> /// <param name="applicationConfig"></param> /// <returns></returns> private static async Task ConsulHandlerAsync(ApplicationConfig applicationConfig) { _consulHelper = new ConsulHelper(applicationConfig.ConsulConfig, applicationConfig.ServiceConfig); _consulHelper.OnMessage += message => ConsoleHelper.ServerWriteLine(message); _consulHelper.OnException += ConsoleHelper.ServerWriteError; await _consulHelper.RegisterConsulAsync(); }
/// <summary> /// /// </summary> /// <param name="app"></param> public void Configure(IApplicationBuilder app) { if (Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region Swagger app.UseSwagger(); app.UseSwaggerUI(options => { //options.SwaggerEndpoint($"/doc/identityservice/swagger.json", "identityservice"); options.SwaggerEndpoint("/swagger/identityservice/swagger.json", "identityservice"); }); #endregion app.UseStaticFiles(); app.UseRouting(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); ConsulHelper.RegisterService($"http://{LocalInfo.SlbIp}:8500", "dc1", "identityservice", LocalInfo.ServerIp, 5100).Wait(); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/articlemanage/swagger.json", "My API V1"); }); app.UseRouting(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Files")), RequestPath = new Microsoft.AspNetCore.Http.PathString("/api/articlemanage/src") }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); ConsulHelper.RegisterService($"http://{LocalInfo.SlbIp}:8500", "dc1", "articlemanage", LocalInfo.ServerIp, 6010).Wait(); }
public async Task <IActionResult> Index() { var url = $"{ConsulHelper.GetServiceUrl()}api/student"; var res = await WebApiHelper.InvokeApi(url); ViewBag.Students = JsonConvert.DeserializeObject <List <string> >(res); return(View()); }
public string GetNameByService(string name) { var service = ConsulHelper.GetService(consulAddress: Configuration["ConsulOption:ConsulAddress"], serviceName: Configuration["ConsulOption:ServiceName"]); using (var client = new HttpClient()) { Task <string> result = client.GetStringAsync($"http://{service.ServiceAddress}:{service.ServicePort}/api/ServiceFinder/GetName?name={name}"); return($"{service.ServiceAddress}:{service.ServicePort} -> result :{result.Result}"); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); Settings.AuthorizationKey = Configuration.GetSection("ApplicationSettings:AuthorizationKey")?.Value; Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value; Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value; // Add Application Insights services into service collection services.AddApplicationInsightsTelemetry(); // Add the standard telemetry client services.AddSingleton <TelemetryClient, TelemetryClient>(); // Adding EncryptionKey and ApplicationCode using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(EnvironmentName, ContentRootPath)) { Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value; EncryptionKey = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result; Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value; ApplicationCode = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultApplicationCode).Result; } // Adding Consul hosted service using (ConsulHelper consulHelper = new ConsulHelper(EnvironmentName, ContentRootPath)) { consulHelper.Initialize(services, Configuration); } services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "https://BotApp.Luis.Router.Identity", ValidAudience = "https://BotApp.Luis.Router.Identity", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.AuthorizationKey)) }; }); services.AddCors(o => o.AddPolicy("AllowAllPolicy", options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); }
public async Task <IActionResult> GetProductListAsync() { var service = await ConsulHelper.GetServerAsync(_baskectSettings.CatalogServerName); var client = _httpClientFactory.CreateClient(); var url = $"http://{service.ServiceAddress}:{service.ServicePort}/api/catalog/list"; var response = await client.GetAsync(url); var result = await response.Content.ReadAsStringAsync(); return(Ok(result)); }
private async Task <int> ExecuteAsync(Uri address, string token) { using var client = ConsulHelper.CreateConsulClient(address, token); Console.WriteLine($"Push started. Address: {client?.Config?.Address}"); var usedFiles = Common.GetLocalFiles(); var txnOps = new List <KVTxnOp>(); foreach (var filePath in usedFiles) { var consulPath = Path.GetRelativePath(Common.BaseDirectoryFullPath, filePath).ToUnixPath(); var textContent = await File.ReadAllTextAsync(filePath, Encoding.UTF8); txnOps.Add(new KVTxnOp(consulPath, KVTxnVerb.Set) { Value = Encoding.UTF8.GetBytes(textContent) }); Console.WriteLine($"Key: {consulPath}"); } Console.WriteLine($"{txnOps.Count} key(s) prepared. Trying to push..."); foreach (var txnOpsChunk in txnOps.ChunkBy(Common.ConsulTransactionMaximumOperationCount)) { var pushResponse = await client.KV.Txn(txnOpsChunk); if (pushResponse.StatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"{pushResponse.Response.Results.Count} key(s) pushed."); } else { Console.WriteLine($"{pushResponse.Response.Results.Count} key(s) pushed. "); Console.WriteLine($"{pushResponse.Response.Errors.Count} key(s) couldn't be pushed due to errors: "); foreach (var errorMessage in pushResponse.Response.Errors.Select(x => x.What).Distinct()) { Console.WriteLine($"{errorMessage}"); } } } return(0); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); ConsulHelper.AllServiceDeregister(); } app.UseConsul(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("dbconnection"))); var consulClient = new ConsulClient(c => c.Address = new Uri($"http://{ Configuration["Consul:IP"] }:{Configuration["Consul:Port"] }")); ConsulHelper helper = new ConsulHelper(consulClient); services.AddAuthentication(Configuration["Identity:Scheme"]) .AddIdentityServerAuthentication(ops => { ops.RequireHttpsMetadata = false; //ops.Authority = $"http://{Configuration["Identity:IP"]}:{Configuration["Identity:Port"]}"; ops.Authority = helper.GetUri("IdentityService"); ops.ApiName = Configuration["Service:Name"]; }); services.AddSingleton(consulClient); }
public IActionResult Index() { //ViewBag.userInfo= _userInfoServices.GetUserInfoById(1); string uri = "http://AppCoreSample/api/user/get?id=1"; //string content = HttpClientHelper.GetByHttpClient(url); var url = ConsulHelper.GetConsulService(new Uri(uri)); string content = HttpClientHelper.GetByHttpClient(url); //#region consul服务发现 //ConsulClient consulClient = new ConsulClient(x => { // x.Address //}); //#endregion return(View()); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); }); var ret = ConsulHelper.ServiceRegister(Configuration).Result; Console.WriteLine(JsonConvert.SerializeObject(ret, Formatting.Indented)); }
public string GetValue(string key) { return(ConsulHelper.GetValue(consulAddress, key)); }
public LoginUserService(HttpClient httpClient, ConsulHelper consulHelper) { _httpClient = httpClient; _consulHelper = consulHelper; }
private async Task <int> ExecuteAsync(Uri address, string token) { using var client = ConsulHelper.CreateConsulClient(address, token); Console.WriteLine($"Fetch started. Address: {client.Config?.Address}"); var nonFolderPairs = await Common.GetNonFolderPairsAsync(client); if (nonFolderPairs == null) { return(1); } var fetchResults = new List <FetchResult>(); foreach (var nonFolderPair in nonFolderPairs) { var fetchResult = new FetchResult { Key = nonFolderPair.Key }; fetchResults.Add(fetchResult); try { var fileName = Path.Combine(Common.BaseDirectory, nonFolderPair.Key); var content = nonFolderPair.Value == null ? string.Empty : Encoding.UTF8.GetString(nonFolderPair.Value); Directory.CreateDirectory(Path.GetDirectoryName(fileName)); await File.WriteAllTextAsync(fileName, content); fetchResult.IsSucceeded = true; } catch (IOException ex) { fetchResult.IsSucceeded = false; fetchResult.ErrorMessage = $"Key couldn't be fetched. Make sure there is no Key and Folder pair with the same name in the same directory. Error: {ex.Message}"; } catch (Exception ex) { fetchResult.IsSucceeded = false; fetchResult.ErrorMessage = $"Key couldn't be fetched. Error: {ex.Message}"; } } if (fetchResults.All(f => f.IsSucceeded)) { Console.WriteLine("All keys successfully fetched."); return(0); } var unSuccessfulResults = fetchResults.Where(fr => !fr.IsSucceeded).ToList(); await Console.Error.WriteLineAsync($"{unSuccessfulResults.Count} / {fetchResults.Count} key(s) cannot be fetched"); foreach (var fetchResult in unSuccessfulResults) { await Console.Error.WriteLineAsync($"{fetchResult.Key}: {fetchResult.ErrorMessage}"); } return(1); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Reading settings Settings.MicrosoftAppId = Configuration.GetSection("ApplicationSettings:MicrosoftAppId")?.Value; Settings.MicrosoftAppPassword = Configuration.GetSection("ApplicationSettings:MicrosoftAppPassword")?.Value; Settings.BotConversationStorageConnectionString = Configuration.GetSection("ApplicationSettings:BotConversationStorageConnectionString")?.Value; Settings.BotConversationStorageKey = Configuration.GetSection("ApplicationSettings:BotConversationStorageKey")?.Value; Settings.BotConversationStorageDatabaseId = Configuration.GetSection("ApplicationSettings:BotConversationStorageDatabaseId")?.Value; Settings.BotConversationStorageUserCollection = Configuration.GetSection("ApplicationSettings:BotConversationStorageUserCollection")?.Value; Settings.BotConversationStorageConversationCollection = Configuration.GetSection("ApplicationSettings:BotConversationStorageConversationCollection")?.Value; // Adding EncryptionKey and ApplicationCode using (KeyVaultHelper keyVaultHelper = new KeyVaultHelper(EnvironmentName, ContentRootPath)) { Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value; EncryptionKey = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result; Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value; ApplicationCode = keyVaultHelper.GetVaultKeyAsync(Settings.KeyVaultApplicationCode).Result; } // Adding CosmosDB user storage CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions { AuthKey = Settings.BotConversationStorageKey, CollectionId = Settings.BotConversationStorageUserCollection, CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString), DatabaseId = Settings.BotConversationStorageDatabaseId, }); var userState = new UserState(userstorage); services.AddSingleton(userState); // Adding CosmosDB conversation storage CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions { AuthKey = Settings.BotConversationStorageKey, CollectionId = Settings.BotConversationStorageConversationCollection, CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString), DatabaseId = Settings.BotConversationStorageDatabaseId, }); var conversationState = new ConversationState(conversationstorage); services.AddSingleton(conversationState); // Adding Consul hosted service using (ConsulHelper consulHelper = new ConsulHelper(EnvironmentName, ContentRootPath)) { consulHelper.Initialize(services, Configuration); } // Adding MVC compatibility services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Adding the credential provider to be used with the Bot Framework Adapter services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>(); // Adding the channel provider to be used with the Bot Framework Adapter services.AddSingleton <IChannelProvider, ConfigurationChannelProvider>(); // Adding the Bot Framework Adapter with error handling enabled services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Adding middlewares services.AddSingleton(new AutoSaveStateMiddleware(userState, conversationState)); services.AddSingleton(new ShowTypingMiddleware()); // Add Application Insights services into service collection services.AddApplicationInsightsTelemetry(); // Add the standard telemetry client services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>(); // Add ASP middleware to store the HTTP body, mapped with bot activity key, in the httpcontext.items // This will be picked by the TelemetryBotIdInitializer services.AddTransient <TelemetrySaveBodyASPMiddleware>(); // Add telemetry initializer that will set the correlation context for all telemetry items services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>(); // Add telemetry initializer that sets the user ID and session ID (in addition to other // bot-specific properties, such as activity ID) services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>(); // Create the telemetry middleware to track conversation events services.AddSingleton <IMiddleware, TelemetryLoggerMiddleware>(); // Adding LUIS Router accessor services.AddSingleton(sp => { LuisRouterAccessor accessor = null; using (LuisRouterHelper luisRouterHelper = new LuisRouterHelper(EnvironmentName, ContentRootPath)) { accessor = luisRouterHelper.BuildAccessor(userState, sp.GetRequiredService <IBotTelemetryClient>()); } return(accessor); }); // Adding QnAMaker Router accessor services.AddSingleton(sp => { QnAMakerAccessor accessor = null; using (QnAMakerHelper qnaMakerHelper = new QnAMakerHelper(EnvironmentName, ContentRootPath)) { accessor = qnaMakerHelper.BuildAccessor(); } return(accessor); }); // Adding accessors services.AddSingleton(sp => { // We need to grab the conversationState we added on the options in the previous step var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors"); } // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new BotAccessors(loggerFactory, conversationState, userState) { ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"), AskForExamplePreference = conversationState.CreateProperty <bool>("AskForExamplePreference"), IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference") }; return(accessors); }); // Adding the bot as a transient. In this case the ASP Controller is expecting an IBot services.AddTransient <IBot, BotAppBot>(); }
public bool SetKV(string key, string value) { return(ConsulHelper.SetKeyValue(consulAddress, key, value)); }
public string Get() { var service = ConsulHelper.GetService(consulAddress: Configuration["ConsulOption:ConsulAddress"], serviceName: Configuration["ConsulOption:ServiceName"]); return($@"CatalogService:{JsonConvert.SerializeObject(service)}"); }