Skip to content

Commit ab5f7b0

Browse files
committed
完善节点重定向逻辑,添加节点端口配置,更新节点URL获取方法
1 parent 75b8fa8 commit ab5f7b0

4 files changed

Lines changed: 49 additions & 5 deletions

File tree

Controllers/ContentController.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,21 @@ public async Task<IActionResult> GetFile(string hash)
6363
if (availableNodes.Any())
6464
{
6565
var targetNode = availableNodes.First();
66-
return Redirect($"{targetNode.Url}/content/{hash}");
66+
if (targetNode?.Url == null)
67+
{
68+
return StatusCode(500, "Invalid node configuration");
69+
}
70+
71+
if (!Uri.TryCreate(targetNode.Url, UriKind.Absolute, out var uri))
72+
{
73+
_logger.LogError("Invalid node URL format: {Url}", targetNode.Url);
74+
return StatusCode(500, "Invalid node configuration");
75+
}
76+
77+
// 使用配置的主域名,使用 HTTPS,忽略原始端口
78+
var redirectUrl = $"https://{uri.Host}.{_config.MainDomain}/content/{hash}";
79+
_logger.LogInformation("Redirecting request to: {RedirectUrl}", redirectUrl);
80+
return Redirect(redirectUrl);
6781
}
6882

6983
return NotFound("No available nodes to serve the content");

Models/NodeConfig.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,8 @@ public class NodeConfig
1919

2020
public TimeSpan DirectoryScanInterval { get; set; } = TimeSpan.FromMinutes(10);
2121

22+
[Required]
23+
public int Port { get; set; } = 5000; // 默认端口号为5000
24+
2225
public string StorageDirectory { get; set; } = "Storage";
2326
}

MultiSourceContentDelivery.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<PackageReference Include="Polly" Version="8.6.2" />
1515
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
1616
<PackageReference Include="System.Threading.Tasks" Version="4.3.0" />
17+
<PackageReference Include="System.Net.NetworkInformation" Version="4.3.0" />
1718
</ItemGroup>
1819

1920
</Project>

Services/DirectoryScanService.cs

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
using MultiSourceContentDelivery.DbContexts;
33
using MultiSourceContentDelivery.Models;
44
using System.Net.Http.Json;
5+
using System.Net.NetworkInformation;
6+
using System.Net;
57
using Polly;
68
using Polly.Retry;
79
using FileInfo = MultiSourceContentDelivery.Models.FileInfo;
@@ -165,16 +167,17 @@ private async Task ScanDirectoryAndUpdateDatabase(CancellationToken stoppingToke
165167
ContentType = GetContentType(file),
166168
Size = new IOFileInfo(file).Length,
167169
LocalPath = relPath,
168-
AvailableNodes = new List<string> { $"http://{Environment.MachineName}" }
170+
AvailableNodes = new List<string> { GetNodeUrl() }
169171
};
170172
await context.FileInfos.AddAsync(fileInfo);
171173
}
172174
else
173175
{
174176
fileInfo.LocalPath = relPath;
175-
if (!fileInfo.AvailableNodes.Contains($"http://{Environment.MachineName}"))
177+
var nodeUrl = GetNodeUrl();
178+
if (!fileInfo.AvailableNodes.Contains(nodeUrl))
176179
{
177-
fileInfo.AvailableNodes.Add($"http://{Environment.MachineName}");
180+
fileInfo.AvailableNodes.Add(nodeUrl);
178181
}
179182
}
180183
}
@@ -206,7 +209,7 @@ private async Task SyncWithOtherNodes(CancellationToken stoppingToken)
206209
// 更新本节点信息
207210
var nodeInfo = new NodeInfo
208211
{
209-
Url = $"http://{Environment.MachineName}",
212+
Url = GetNodeUrl(),
210213
AvailableStorageBytes = await GetAvailableStorageAsync(),
211214
CurrentLoad = await GetCurrentLoadAsync(),
212215
LastSeen = DateTime.UtcNow
@@ -352,4 +355,27 @@ private string GetContentType(string filePath)
352355
_ => "application/octet-stream"
353356
};
354357
}
358+
359+
private string GetNodeUrl()
360+
{
361+
try
362+
{
363+
// 获取本机所有网络接口的IP地址
364+
var ipAddress = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
365+
.Where(n => n.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
366+
.SelectMany(n => n.GetIPProperties().UnicastAddresses)
367+
.Where(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
368+
&& !System.Net.IPAddress.IsLoopback(a.Address))
369+
.Select(a => a.Address.ToString())
370+
.FirstOrDefault();
371+
372+
// 如果找不到合适的IP地址,使用localhost
373+
return $"http://{ipAddress ?? "localhost"}";
374+
}
375+
catch (Exception ex)
376+
{
377+
_logger.LogError(ex, "Error getting node URL, falling back to localhost");
378+
return $"http://localhost";
379+
}
380+
}
355381
}

0 commit comments

Comments
 (0)