From 866a5c57e3add8098f37f8bb373311954576f6c8 Mon Sep 17 00:00:00 2001 From: Mohammad Mahdi Date: Wed, 20 Aug 2025 14:22:48 +0330 Subject: [PATCH] Refactor route handling to use `ConcurrentDictionary` for thread-safe updates and optimize `/goto/{path}` logic --- VirtualDDNSRouter.Server/Program.cs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/VirtualDDNSRouter.Server/Program.cs b/VirtualDDNSRouter.Server/Program.cs index 4a293ed..7a2dfd8 100644 --- a/VirtualDDNSRouter.Server/Program.cs +++ b/VirtualDDNSRouter.Server/Program.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using Microsoft.AspNetCore.HttpOverrides; using VirtualDDNSRouter.Server.Interfaces; using VirtualDDNSRouter.Server.Services; @@ -21,7 +22,7 @@ app.UseForwardedHeaders(new ForwardedHeadersOptions if (app.Environment.IsDevelopment()) app.MapOpenApi(); -var routes = new List(); +var routes = new ConcurrentDictionary(); app.MapGet("/setip/{path}/{port}/{apiKey}", async (IYamlParser yamlParser, HttpContext context, string path, ushort port, string apiKey) => @@ -42,24 +43,20 @@ app.MapGet("/setip/{path}/{port}/{apiKey}", return Results.BadRequest("Could not get the client ip address"); } - var existingRoute = routes.FirstOrDefault(r => r.path == path); - if (existingRoute is not null) routes.Remove(existingRoute); - - routes.Add(new Route + routes[path] = new Route { ipAddress = clientIp, path = path, port = port - }); + }; return Results.Ok($"goto/{path}"); }); app.MapGet("/goto/{path}", (string path) => { - var redirectRoute = routes.FirstOrDefault(r => r.path == path); - if (redirectRoute is null) return Task.FromResult(Results.NotFound()); - return Task.FromResult(Results.Redirect($"http://{redirectRoute.ipAddress}:{redirectRoute.port}")); + if (routes.TryGetValue(path, out var route)) return Results.Redirect($"http://{route.ipAddress}:{route.port}"); + return Results.NotFound(); }); app.Run(); \ No newline at end of file