gpt4 book ai didi

c# - 我怎样才能可靠地获得实际的 URL,即使路径中有百分比编码的部分?

转载 作者:可可西里 更新时间:2023-11-01 03:00:13 24 4
gpt4 key购买 nike

IIS 和 ASP.NET (MVC) has some glitchespath 中使用带有 %-encoding 的 url 时(不是查询字符串;查询字符串很好)。我该如何解决这个问题?即我怎样才能得到请求的实际 URL?

例如,如果我导航到 /x%3Fa%3Db 并(分别)导航到 /x?a=b - 它们都报告 .Request.Url as /x?a=b - 因为路径中的编码数据 报错了。

最佳答案

我解决这个问题的方法是查看底层服务器变量; URL 变量包含一个解码 值; QUERY_STRING 变量包含仍然编码的查询。我们不能只在 URL 部分调用 encode,因为它还包含原始形式的原始 / 等 - 如果我们盲目编码整个事情我们会得到不需要的 %2f 值;但是,可以将其拆开并发现有问题的情况:

private static readonly Regex simpleUrlPath = new Regex("^[-a-zA-Z0-9_/]*$", RegexOptions.Compiled);
private static readonly char[] segmentsSplitChars = { '/' };
// ^^^ avoids lots of gen-0 arrays being created when calling .Split
public static Uri GetRealUrl(this HttpRequest request)
{
if (request == null) throw new ArgumentNullException("request");
var baseUri = request.Url; // use this primarily to avoid needing to process the protocol / authority
try
{
var vars = request.ServerVariables;
var url = vars["URL"];
if (string.IsNullOrEmpty(url) || simpleUrlPath.IsMatch(url)) return baseUri; // nothing to do - looks simple enough even for IIS

var query = vars["QUERY_STRING"];
// here's the thing: url contains *decoded* values; query contains *encoded* values

// loop over the segments, encoding each separately
var sb = new StringBuilder(url.Length * 2); // allow double to be pessimistic; we already expect trouble
var segments = url.Split(segmentsSplitChars);
foreach (var segment in segments)
{
if (segment.Length == 0)
{
if(sb.Length != 0) sb.Append('/');
}
else if (simpleUrlPath.IsMatch(segment))
{
sb.Append('/').Append(segment);
}
else
{
sb.Append('/').Append(HttpUtility.UrlEncode(segment));
}
}
if (!string.IsNullOrEmpty(query)) sb.Append('?').Append(query); // query is fine; nothing needing
return new Uri(baseUri, sb.ToString());
}
catch (Exception ex)
{ // if something unexpected happens, default to the broken ASP.NET handling
GlobalApplication.LogException(ex);
return baseUri;
}
}

关于c# - 我怎样才能可靠地获得实际的 URL,即使路径中有百分比编码的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15117342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com