diff --git a/Reportapi/MyCode.Project.WebApi/Controllers/TestController.cs b/Reportapi/MyCode.Project.WebApi/Controllers/TestController.cs index 93dba13..2910ea3 100644 --- a/Reportapi/MyCode.Project.WebApi/Controllers/TestController.cs +++ b/Reportapi/MyCode.Project.WebApi/Controllers/TestController.cs @@ -5,6 +5,7 @@ using MyCode.Project.Services.Implementation; using MyCode.Project.Services.IServices; using System; using System.Collections.Generic; +using System.Text.RegularExpressions; using System.Web.Http; namespace MyCode.Project.WebApi.Controllers @@ -103,6 +104,34 @@ namespace MyCode.Project.WebApi.Controllers } #endregion + /// + /// 替换或添加URL中的端口号(支持指定协议) + /// + /// + /// + /// + /// + [HttpGet] + [AllowAnonymous] + public string ReplaceOrAddPortAdvanced(string input, string newPort, string protocol = "http") + { + // 构建协议特定的模式 + string protocolPattern = string.IsNullOrEmpty(protocol) ? @"(https?|ftp)://" : $"{protocol}://"; + + // 匹配已有端口号 + string patternWithPort = $@"({protocolPattern}[^/]+?):\d+"; + // 匹配没有端口号 + string patternWithoutPort = $@"({protocolPattern}[^/:/]+)(?=/|$)"; + + // 先尝试替换已有端口号 + string result = Regex.Replace(input, patternWithPort, $"$1:{newPort}"); + + // 如果没有端口号被替换,尝试添加端口号 + if (result == input) + result = Regex.Replace(input, patternWithoutPort, $"$1:{newPort}"); + + return result; + } //#region 订单查询