C# 利用Yarp做网关访问dapr

  1. 添加Yarp.ReverseProxy

  1. 修改Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.AddYarpProxy();
....
var app = builder.Build();
app.MapReverseProxy();
...
app.Run();
  1. AddYarpProxy定义

public static partial class Extensions
    {
        public static WebApplicationBuilder AddYarpProxy(this WebApplicationBuilder builder)
        {            
            builder.Services.AddReverseProxy()
                .LoadFromMemory(DaprConfigUtils.Routes, DaprConfigUtils.Clusters)
                .AddTransforms<DaprTransformProvider>();
            return builder;
        }
    }

public class DaprConfigUtils
    {
        public const string DaprApiRouteId = "dapr-service";
        public const string DaprApiClusterId = "dapr-sidecar";
        public const string DaprApiStartBy = "/api/";
        public static RouteConfig[] Routes => new[]
            {
                new RouteConfig(){
                    RouteId = DaprApiRouteId, 
                    ClusterId = DaprApiClusterId,
                    Match = new RouteMatch
                    {                        
                        Path = DaprApiStartBy + "{**catch-all}"
                    }
                }
            };
        public static ClusterConfig[] Clusters => new[]
            {
                new ClusterConfig()
                {
                    ClusterId = DaprApiClusterId,
                    //SessionAffinity = new SessionAffinityConfig { Enabled = true, Policy = "Cookie", AffinityKeyName = ".Yarp.ReverseProxy.Affinity" },
                    Destinations = new Dictionary<string, DestinationConfig>(StringComparer.OrdinalIgnoreCase)
                    {
                        { "destination1", new DestinationConfig() { Address = "http://127.0.0.1:3500" } },
                    }
                }
            };
    }
  1. 定义DaprTransformProvider

public class DaprTransformProvider : ITransformProvider
    {
        public void Apply(TransformBuilderContext context)
        {
            if (context.Route.RouteId == DaprConfigUtils.DaprApiRouteId)
            {
                context.AddRequestTransform( (RequestTransformContext transformContext) =>{
                    var path = transformContext.Path.Value?.Replace(DaprConfigUtils.DaprApiStartBy,string.Empty);
                    if (!string.IsNullOrEmpty(path))
                    {
                        var index = path.IndexOf('/');
                        if (index != -1)
                        {
                            var appId = path.Substring(0, index);
                            var newPath = path.Substring(index);
                            if (!string.IsNullOrEmpty(appId) && !string.IsNullOrEmpty(newPath))
                            {
                                transformContext.ProxyRequest.RequestUri = new Uri($"{transformContext.DestinationPrefix}/v1.0/invoke/{appId}/method{newPath}");
                                return ValueTask.CompletedTask;
                            }
                        }
                    }
                    return ValueTask.FromException(new Exception($"路径错误,必须格式/api/appid/*,实际:{transformContext.Path}"));
                });
            }
        }

        public void ValidateCluster(TransformClusterValidationContext context)
        {
            /*if (context.Cluster.ClusterId== DaprConfigUtils.DaprApiClusterId)
            {
            }*/
        }

        public void ValidateRoute(TransformRouteValidationContext context)
        {
            /*if (context.Route.RouteId == DaprConfigUtils.DaprApiRouteId)
            {
            }*/
        }
    }

搞定!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值