【问题标题】:Passing regular expressions though URL encoding通过 URL 编码传递正则表达式
【发布时间】:2015-07-15 19:23:16
【问题描述】:

我正在尝试使用 Angular JS 客户端和 Nancy FX 服务器端将正则表达式从客户端传递到服务器。我对“+”字符有一个特殊的问题。我目前正在将“+”显式编码为“%2B”客户端:

    this.getMatchingPoints = function (stringMatch) {
        console.log("Application Points Service: getPointsMatching('" + stringMatch + "')");
        /* we have a particular problem with the character '+' in regular expressions, since
         * encodeURIComponent ignores it, and urldecoders treat it as a space. So it must be
         * manually url encoded after passing the rest of the string to encodeURIcomponent */
        var encodedPattern = encodeURIComponent(stringMatch).replace('+', '%2B');
        return $http.get('/Json/PointsMatching/' + encodedPattern);
    };

...但它仍然作为空间服务器端接收。

从某种意义上说,这并不重要,因为正则表达式中的任何实例,例如,“[A-Z]+”都可以替换为“[A-Z][A-Z]*”;或者,或者,我可以使用我自己的特殊解码器服务器端为“+”客户端编写自己的特殊编码器。

但我想知道以前是否有人遇到过这个问题,如果有,他们是如何解决的?

【问题讨论】:

  • 好吧,我诽谤了 encodeURIComponent 的作者;它确实正确地将加号 ('+') 替换为 '%2B'。问题出在世界的南希一侧。这很奇怪,因为 C# HttpUtility.UrlDecode 库函数将“%2B”正确解码为“+”。
  • 您是否尝试过使用 OWIN 而不是旧的 Nancy Self Host 进行自托管?据我所知,OWIN 方式不应该受到双重编码的影响。

标签: javascript regex angularjs nancy


【解决方案1】:

更多调查表明,这是 Nancy FX 中一个深层次且难以解决的错误,开发人员知道这一点;见here。

我的解决方法是,鉴于空格在我正在工作的特定上下文中不是有效字符,将所有空格替换为加号服务器端:

        /* <summary>
         *  Return a JSON formatted document comprising a list of all those application points whose 
         *  names match the regular expression.
         *  </summary>
         *  <remarks>
         *  <para>This entry point is expected to be invoked with the pattern as the final element in the path
         *  (i.e. <code>/Json/PointsMatching/pattern_here</code>). This variant cannot cope with either slashes
         *  or backslashes in the pattern, even if they're URL encoded.</para>
         *  </remarks>
         *  <param name="pattern">A regular expression.</param>
         *  <returns>A JSON formatted document comprising a list of all those application points whose 
         *  names match the regular expression.</returns>
         */
        this.Get["/PointsMatching/{pattern}"] = _ =>
        {
            string pattern = (string)_.pattern;
            /* THIS IS A HACK! The URL decoder used by Nancy decodes both '+' and '%2B' as ' ', which
             * rather defeats the point of url encoding. However, we don't normally use spaces in
             * application point names (although it would be valid to do so), so it's fairly save to
             * replace all spaces in patterns with pluses. */
            pattern = pattern.Replace(" ", "+");

            return this.WithValidUser<string>(pattern, InterestRegistry.Instance.GetPointsMatching);
        };

这显然是丑陋的,不是通用的解决方案,但它现在可以工作。

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多