Javascript 通过URL编码传递正则表达式
我正在尝试使用Angular JS客户端和Nancy FX服务器端将正则表达式从客户端传递到服务器。我对“+”字符有一个特殊的问题。我当前将“+”显式编码为“%2B”客户端:Javascript 通过URL编码传递正则表达式,javascript,regex,angularjs,nancy,Javascript,Regex,Angularjs,Nancy,我正在尝试使用Angular JS客户端和Nancy FX服务器端将正则表达式从客户端传递到服务器。我对“+”字符有一个特殊的问题。我当前将“+”显式编码为“%2B”客户端: this.getMatchingPoints = function (stringMatch) { console.log("Application Points Service: getPointsMatching('" + stringMatch + "')"); /* we h
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]*”;或者,我也可以用自己的专用解码器服务器端为“+”客户端编写自己的专用编码器
但是我想知道以前是否有人遇到过这个问题,如果是的话,他们是如何解决的?更多的调查表明,这是Nancy FX中一个深层次的、难以解决的错误,开发者都知道;看 我的解决方法是,假设在我工作的特定上下文中,空格不是有效字符,用pluses服务器端替换所有空格:
/* <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);
};
这显然很难看,不是一个通用的解决方案,但它目前还有效。好吧,我诽谤了encodeURIComponent的作者;它确实正确地将加号(“+”)替换为“%2B”。问题出在世界的南希一边。这很奇怪,因为C#HttpUtility.UrlDecode库函数正确地将“%2B”解码为“+”。您是否尝试过使用OWIN而不是旧的Nancy自宿主进行自宿主?据我记忆所及,OWIN way不应该遭受双重编码。