18

IIS 和 ASP.NET (MVC)在使用路径中带有 %-encoding 的 url 时会出现一些故障(不是查询字符串;查询字符串很好)。我怎样才能解决这个问题?即我怎样才能得到请求的实际 URL?

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

4

1 回答 1

21

我解决这个问题的方法是查看底层服务器变量;该URL变量包含一个解码值;该QUERY_STRING变量包含仍然编码的查询。我们不能只在零件上调用encodeURL,因为它还包含/原始形式的原始等 - 如果我们盲目地对整个事物进行编码,我们将得到不需要的%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;
    }
}
于 2013-02-27T16:35:57.190 回答