chenhaozhe
2026-11-11 4837024d8cd40e31bb4b95cbeec0ae473dfca4e3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
 
namespace APIGetway.Filter
{
    /// <summary>
    /// 计算"内部地址"主机集合:回环地址 + 所有 YARP 后端目的地主机 + 配置中额外声明的主机。
    /// LocationRewriteFilter 与 UpstreamErrorPageFilter 共用。
    /// </summary>
    internal static class InternalHostSet
    {
        private static readonly string[] LoopbackHosts =
        {
            "localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"
        };
 
        internal static HashSet<string> Build(IConfiguration configuration, string extraSection, string extraKey)
        {
            var comparer = StringComparer.OrdinalIgnoreCase;
            var hosts = new HashSet<string>(LoopbackHosts, comparer);
 
            foreach (var cluster in configuration.GetSection("ReverseProxy:Clusters").GetChildren())
            {
                foreach (var destination in cluster.GetSection("Destinations").GetChildren())
                {
                    var address = destination["Address"];
                    if (Uri.TryCreate(address, UriKind.Absolute, out var uri) && !string.IsNullOrEmpty(uri.Host))
                    {
                        hosts.Add(uri.Host);
                    }
                }
            }
 
            foreach (var extra in configuration.GetSection(extraSection).GetSection(extraKey).GetChildren())
            {
                if (!string.IsNullOrWhiteSpace(extra.Value))
                {
                    hosts.Add(extra.Value.Trim());
                }
            }
 
            return hosts;
        }
    }
}