.Netcore 2.0 Ocelot Api网关教程(6)- 配置管理
本文介紹Ocelot中的配置管理,配置管理允許在Api網(wǎng)關(guān)運(yùn)行時(shí)動(dòng)態(tài)通過Http Api查看/修改當(dāng)前配置。由于該功能權(quán)限很高,所以需要授權(quán)才能進(jìn)行相關(guān)操作。有兩種方式來認(rèn)證,外部Identity Server或內(nèi)部Identity Server。
1、外部Identity Server
修改 Startup 中的 ConfigureServices 方法如下:
public void ConfigureServices(IServiceCollection services){
services.AddMvc();
void options(IdentityServerAuthenticationOptions o)
{
o.Authority = "http://localhost:6000";
o.RequireHttpsMetadata = false;
o.ApiName = "api1";
}
services
.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.json")
.Build())
.AddAdministration("/administration", options);
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication("TestKey", options);
}
其中復(fù)用了Identity Server的配置。
2、內(nèi)部Identity Server
修改 Startup 中的 ConfigureServices 方法如下:
public void ConfigureServices(IServiceCollection services){
services.AddMvc();
services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.json")
.Build())
.AddAdministration("/administration", "secret");
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication("TestKey", options =>
{
options.Authority = "http://localhost:6000";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
}
其中為secret值為"secret",后邊會(huì)用得到。
其上為添加配置管理的兩種方式,本例中以內(nèi)部Identity Server為例。
Administration一共提供了3組Api
Token獲取
配置管理
緩存管理
其中Token獲取Api只在使用內(nèi)部Identity Server時(shí)有效。由于緩存的教程還沒更新,所以緩存管理的Api在后邊的文章介紹。
1、Token獲取
使用Postman請(qǐng)求http://localhost:5000/administration/connect/token如下所示,可以獲得一個(gè)token
token from internal id server.png
注意Body的數(shù)據(jù)類型要選擇 form-data,并且 client_secret 要填寫代碼中配置的secret,當(dāng)前教程為secret。
2、配置管理
使用Postman請(qǐng)求http://localhost:5000/administration/configuration如下所示,獲取配置
get configuration.png
使用上次獲取的token。
以http://localhost:5000/GetUserInfo?name=Jonathan為例請(qǐng)求數(shù)據(jù)如下
GetUserInfo.png
可以成功請(qǐng)求并且獲取數(shù)據(jù)。
然后修改配置如下
change configuration.png
注意此次請(qǐng)求為Post請(qǐng)求,并且不要忘記添加認(rèn)證頭token,此次請(qǐng)求的body參數(shù)為之前獲取的配置并且修改了/GetUserInfo鏈接為/GetUserInfochanged。
再次使用Postman請(qǐng)求http://localhost:5000/GetUserInfo?name=Jonathan如下
GetUserInfo 404.png
得到了404,修改鏈接為http://localhost:5000/GetUserInfochanged?name=Jonathan再次請(qǐng)求如下
GetUserInfochanged.png
此次配置修改成功,打開到路徑/OcelotTutorial/OcelotGetway/bin/Debug/netcoreapp2.0下有一個(gè) configuration.Development.json 文件打開查看如下
configuration.Development.json.png
配置文件也已經(jīng)修改。
可能在開發(fā)時(shí)會(huì)遇到修改完配置之后,下次調(diào)試時(shí)配置又回到了原來,是因?yàn)?configuration.json 選擇成了總是復(fù)制,所以每次開始調(diào)試的時(shí)候都會(huì)替換 configuration.development.json 中的內(nèi)容。
如果Ocelot Api網(wǎng)關(guān)程序沒有讀寫文件的權(quán)限也會(huì)遇到修改配置失敗的情況。
?
原文地址:https://www.jianshu.com/p/9e2fa5783211
.NET社區(qū)新聞,深度好文,歡迎訪問公眾號(hào)文章匯總 http://www.csharpkit.com
總結(jié)
以上是生活随笔為你收集整理的.Netcore 2.0 Ocelot Api网关教程(6)- 配置管理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【ASP.NET Core 沉思录】Cr
- 下一篇: asp.net ajax控件工具集 Au