多くの試行錯誤の末、私は自分の問題に対する非常に醜く、完全に非論理的な解決策を見つけました。それでも... この投稿が将来誰かを助けることができるかもしれません。この「解決策」は.NET 4.5で機能することに注意してください。私はそれがあなたのために働くことを保証しません.
問題は次のようになります。
- エスケープされたスラッシュを .NET の Uri に入れることは (AFAIK) 不可能です
- 外部サービス (RabbitMQ) と通信するために、リクエスト URL に %2f (つまりスラッシュ) を入れることができるようにする必要があります
次の投稿は、私を「正しい」方向に導きました: System.Uri アンエスケープ スラッシュ文字を停止する方法
投稿で提案された解決策を試しましたが...無駄に
その後、多くの呪い、グーグル、リバース エンジニアリングなどを行った後、次のコードを思いつきました。
/// <summary>
/// Client enpoint behavior that enables the use of a escaped forward slash between 2 forward slashes in a url
/// </summary>
public class EncodeForwardSlashBehavior:IEndpointBehavior
{
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new ForwardSlashUrlInspector());
}
}
/// <summary>
/// Inspector that modifies a an Url replacing /// with /%2f/
/// </summary>
public class ForwardSlashUrlInspector:IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
string uriString = request.Headers.To.ToString().Replace("///", "/%2f/");
request.Headers.To = new Uri(uriString);
AddAllowAnyOtherHostFlagToHttpUriParser();
return null;
}
/// <summary>
/// This is one of the weirdest hacks I ever had to do, so no guarantees can be given to this working all possible scenarios
/// What this does is, it adds the AllowAnyOtherHost flag to the private field m_Flag on the UriParser for the http scheme.
/// Replacing /// with /%2f/ in the request.Headers.To uri BEFORE calling this method will make sure %2f remains unescaped in your Uri
/// Why does this work, I don't know!
/// </summary>
private void AddAllowAnyOtherHostFlagToHttpUriParser()
{
var getSyntaxMethod =
typeof(UriParser).GetMethod("GetSyntax", BindingFlags.Static | BindingFlags.NonPublic);
if (getSyntaxMethod == null)
{
throw new MissingMethodException("UriParser", "GetSyntax");
}
var uriParser = getSyntaxMethod.Invoke(null, new object[] { "http" });
var flagsField =
uriParser.GetType().BaseType.GetField("m_Flags", BindingFlags.Instance|BindingFlags.NonPublic);
if (flagsField == null)
{
throw new MissingFieldException("UriParser", "m_Flags");
}
int oldValue = (int)flagsField.GetValue(uriParser);
oldValue += 4096;
flagsField.SetValue(uriParser, oldValue);
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
}
したがって、基本的には、リフレクションを使用して列挙型フラグを UriParser 内のプライベート変数に追加するカスタム EndpointBehavior を作成しています。これにより、request.Headers.To uri でエスケープされたスラッシュがエスケープされないようです。