使用
在 Startup 里
ConfigurationServices 配置 mvc 和 Ocelot
Configure 方法里配置 ocelot 和 mvc
- App.UseOcelotWhenRouteMatch((ocelotBuilder, pipelineConfiguration) =>
- {
- // This is registered to catch any global exceptions that are not handled
- // It also sets the Request Id if anything is set globally
- ocelotBuilder.UseExceptionHandlerMiddleware();
- // This is registered first so it can catch any errors and issue an appropriate response
- ocelotBuilder.UseResponderMiddleware();
- ocelotBuilder.UseDownstreamRouteFinderMiddleware();
- ocelotBuilder.UseDownstreamRequestInitialiser();
- ocelotBuilder.UseRequestIdMiddleware();
- ocelotBuilder.UseMiddleware();
- ocelotBuilder.UseLoadBalancingMiddleware();
- ocelotBuilder.UseDownstreamUrlCreatorMiddleware();
- ocelotBuilder.UseOutputCacheMiddleware();
- ocelotBuilder.UseMiddleware();
- // cors headers
- ocelotBuilder.UseMiddleware();
- });
- App.UseMvc();
新建一个 TestController
- [Route("/api/[controller]")]
- public class TestController : ControllerBase
- {
- public IActionResult Get()
- {
- return Ok(new
- {
- Tick = DateTime.UtcNow.Ticks,
- Msg = "Hello Ocelot",
- });
- }
- }
具体代码可以参考这个 网关示例项目
示例项目的 Ocelot 配置是存在 Redis 里面的, 配置的 ReRoutes 如下:
- {
- "ReRoutes": [
- {
- "DownstreamPathTemplate": "/api.php?key=free&appid=0&msg={everything}",
- "UpstreamPathTemplate": "/api/chat/{everything}",
- "UpstreamHttpMethod": [
- "Get",
- "POST",
- "PUT",
- "PATCH",
- "DELETE",
- "OPTIONS"
- ],
- "AddHeadersToRequest": {
- },
- "RequestIdKey": "RequestId",
- "ReRouteIsCaseSensitive": false,
- "ServiceName": "",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "api.qingyunke.com",
- "Port": 80
- }
- ],
- "DangerousAcceptAnyServerCertificateValidator": false
- }
- ],
- "GlobalConfiguration": {
- "HttpHandlerOptions": {
- "AllowAutoRedirect": false,
- "UseCookieContainer": false,
- "UseTracing": false
- }
- }
- }
运行项目进行测试:
访问 Ocelot 定义的路由 https://localhost:65125/API/chat/hello , 返回信息如图所示:
访问 Mvc 定义的路由 https://localhost:65125/API/test, 返回信息如图所示:
上面正常的返回就表示我们的 Ocelot 和 Mvc 同时工作了~
来源: https://www.2cto.com/kf/201905/809607.html