0%

使用YARP初步替代静态文件+API转发

使用YARP 来替代静态文件+API转发。

graph TD
    A[YARP] -->|Static File| B[wwwroot]
    A --> |/api-dst1| C[EndPoint1] 
    A --> |/api-dst2| D[EndPoint2] 

    style A fill:white,stroke-width:1px 
    style B fill:white,stroke-width:1px

要实现的目的:优先返回本地文件,然后转发到YARP配置的EndPoint。

假设使用.NET 6
创建项目、添加YARP依赖

1
2
3
dotnet new web -n MyYarp
cd MyYarp
dotnet add package Yarp.ReverseProxy

在项目下目录下添加wwwroot文件夹,并且在wwwroot文件夹下添加一个index.html文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
This is the index page
</body>
</html>

修改csproj文件,确保wwwroot目录在编译发布时会被复制

1
2
3
4
5
<ItemGroup>
<None Include="wwwroot\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

修改Program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); // 设置Yarp读取
var app = builder.Build();

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapReverseProxy();
});
app.Run();

修改appsettings.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"ReverseProxy": {
"Routes": {
"route1" : {
"ClusterId": "cluster1",
"Match": {
"Path": "{**catch-all}"
},
}
},
"Clusters": {
"cluster1": {
"Destinations": {
"destination1": {
"Address": "https://example.com/"
}
}
}
}
}
}