URL作为查询字符串传递给controller时仅收到半段如何解决
问题根因
你要传递的目标URL本身包含&字符,该字符是URL查询字符串的默认参数分隔符。当你直接把未编码的URL拼接到请求的查询字符串中时,服务端会将第一个&之后的内容识别为整个请求的独立查询参数,而非URL参数的内容,因此URL参数只会读取到第一个&之前的内容,出现截断问题。
解决方案
- 方案一:前端对URL参数做编码处理
使用encodeURIComponent()方法对要传递的URL参数进行编码,将&、?等特殊字符转义后再拼接,ASP.NET Core后端会自动对查询参数做解码,无需额外处理即可拿到完整URL:
export async function sendNotification(PlanId: string, URL: string) { console.log("Service URL : - ", URL); const encodedUrl = encodeURIComponent(URL); let url = HttpClient.buildUrl(`api/smsNotification/${PlanId}?URL=${encodedUrl}`); return await HttpClient.get(url); }
- 方案二:改为POST请求传递参数
如果后续参数内容较长或存在更多特殊字符,建议改用POST请求将参数放在请求体中传递,彻底避免URL特殊字符和长度限制问题:
前端调整为POST请求:
export async function sendNotification(PlanId: string, URL: string) { console.log("Service URL : - ", URL); let url = HttpClient.buildUrl(`api/smsNotification/${PlanId}`); return await HttpClient.post(url, { URL: URL }); }
后端调整接口接收逻辑:
[HttpPost("Notification/{PlanId}")] [ValidateModelState] public async Task<IActionResult> SendNotification(Guid PlanId, [FromBody] UrlRequest request) { // request.URL 即为完整原始URL return NoContent(); } // 定义请求参数类 public class UrlRequest { public string URL { get; set; } }
内容的提问来源于stack exchange,提问作者Raneu
相关产品推荐
相关产品推荐

