.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现 (2)

添加 ASP.Net Core Web 项目,这里以 ServiceA 为例进行构建

.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现

添加 ASP.Net Core API

.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现

在 StartUp.cs 中添加内容如下:
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ServiceA
{
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "http://127.0.0.1:8021"; options.RequireHttpsMetadata = false; options.Audience = "ServiceA"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); app.UseMvc(); } }

}

```

添加 SessionController 用于用户登录,内容如下:
``` csharp
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;

namespace ServiceA.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SessionController : ControllerBase
{
public async Task Login(UserRequestModel userRequestModel)
{
// discover endpoints from metadata
var client = new HttpClient();
DiscoveryResponse disco = await client.GetDiscoveryDocumentAsync(":8021");
if (disco.IsError)
{
return "认证服务器未启动";
}
TokenResponse tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "ServiceAClient",
ClientSecret = "ServiceAClient",
UserName = userRequestModel.Name,
Password = userRequestModel.Password
});

return tokenResponse.IsError ? tokenResponse.Error : tokenResponse.AccessToken; } } public class UserRequestModel { [Required(ErrorMessage = "用户名称不可以为空")] public string Name { get; set; } [Required(ErrorMessage = "用户密码不可以为空")] public string Password { get; set; } }

}
```

添加 HealthController 用于 Consul 进行服务健康检查,内容如下:
```csharp
using Microsoft.AspNetCore.Mvc;

namespace ServiceA.Controllers
{
[Route("api/[controller]"), ApiController]
public class HealthController : ControllerBase
{
///
/// 健康检查
///
///
[HttpGet]
public IActionResult Get()
{
return Ok();
}
}
}
```

更改 ValuesController.cs 内容如下:
``` csharp
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ServiceA.Controllers
{
[Authorize] //添加 Authorize Attribute 以使该控制器启用认证
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable> Get()
{
return new[] { "value1", "value2" };
}
}
}
```

注意,以上基本完成了 ServiceA 的服务构建,但在实际应用中应做一些修改,例如:IdentityServer 地址应在 appsettings.json 中进行配置,不应把地址分散于项目中各处;认证服务启用最好在全局启用,以防止漏写等等。ServiceB 的内容与 ServiceA 大致相似,因此文章中将不再展示 ServiceB 的构建过程。

Gateway 构建

添加ASP.Net Web

.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现

添加空项目

.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现

打开程序包管理器控制台输入命令:
csharp install-package Ocelot //添加 Ocelot
csharp install-package Ocelot.Provider.Consul // 添加 Consul 服务发现

添加 ocelot.json 文件,内容如下
json { "ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "UpstreamPathTemplate": "/ServiceA/{everything}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ], "ServiceName": "ServiceA", //consul 服务中 ServiceA 的名称 "LoadBalancerOptions": { "Type": "LeastConnection" } }, { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "UpstreamPathTemplate": "/ServiceB/{everything}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ], "ServiceName": "ServiceB", //consul 服务中 ServiceB 的名称 "LoadBalancerOptions": { "Type": "LeastConnection" } } ], "GlobalConfiguration": { "ServiceDiscoveryProvider": { // Consul 服务发现配置 "Host": "localhost", // Consul 地址 "Port": 8500, "Type": "Consul" } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyypzp.html