C#如何从含嵌套URL参数的查询字符串中获取完整重定向URL
解决嵌套URL查询参数被截断的问题
问题根源
你遇到的问题是因为原URL中redirect_url的参数值没有正确编码——目标URL里的&被当成了外层URL的参数分隔符,导致ParseQueryString只读取到第一个&之前的内容。
两种解决思路
1. 从根源避免:生成URL时正确编码
如果能控制生成外层URL的逻辑,对redirect_url的完整值进行URL编码,就能彻底解决问题。示例代码:
string targetUrl = "https://example.com?test=11&test2=22&test3=33"; string encodedRedirectUrl = HttpUtility.UrlEncode(targetUrl); string finalUrl = $"https://example.com/login/login.ashx?redirect_url={encodedRedirectUrl}";
生成后的外层URL会是:https://example.com/login/login.ashx?redirect_url=https%3A%2F%2Fexample.com%3Ftest%3D11%26test2%3D22%26test3%3D33
这时用HttpUtility.ParseQueryString就能正确获取完整的redirect_url值,再解码即可:
var queryParams = HttpUtility.ParseQueryString(context.Request.Url.Query); string redirectUrl = HttpUtility.UrlDecode(queryParams.Get("redirect_url"));
2. 处理已存在的未编码URL
如果只能处理当前这种未正确编码的URL,需要手动截取redirect_url参数的完整值:
string queryString = context.Request.Url.Query.TrimStart('?'); int redirectStartIndex = queryString.IndexOf("redirect_url="); if (redirectStartIndex != -1) { // 截取redirect_url=之后的内容 string rawRedirectUrl = queryString.Substring(redirectStartIndex + "redirect_url=".Length); // 检查是否有后续的外层参数(比如&other=xxx),如果有就截断到该位置 int nextParamPos = rawRedirectUrl.IndexOf('&'); if (nextParamPos != -1) { rawRedirectUrl = rawRedirectUrl.Substring(0, nextParamPos); } // 此时rawRedirectUrl就是完整的目标URL }
你的原代码错误原因
你之前的代码HttpUtility.ParseQueryString(HttpUtility.UrlEncode(context.Request.Url.Query))逻辑错误:先对整个查询字符串编码,再解析,这会把原有的&也编码成%26,导致解析后的参数完全不符合预期,自然只能得到截断的结果。
内容的提问来源于stack exchange,提问作者Sander B
相关产品推荐
相关产品推荐

