2013-04-23 79 views
2

想象一下,我想使用WCF調用外部(意味着我無法控制合同)REST服務。 我有以下的合同WCF UriTemplate UrlEncode

[ServiceContract] 
public interface ISomeRestApi 
{ 
    [OperationContract] 
    [WebInvoke(Method = "PUT", UriTemplate = "blablabla/{parameter1}/{parameter2}")] 
    void PutSomething(string parameter1, string parameter2); 
} 

再說說我的參數之一是正斜槓(/)

public class Test{ 

    [Fact] 
    public void TestPutSomething() 
    { 
     ISomeRestApi api = CreateApi(); 

     //this results in the url: http://server/blablabla///someotherparam 
     api.PutSomething("/", "someotherparam"); 

     //this also results in the url: http://server/blablabla///someotherparam 
     api.PutSomething(HttpUtility.UrlEncode("/"), "someotherparam"); 

     //but i want: http://server/blablabla/%2F/someotherparam 
    } 
} 

如何強制WCF來urlencode我UriTemplate路徑參數?

+0

可能的重複[如何將斜槓和其他'url敏感'字符傳遞給WCF REST服務?](http://stackoverflow.com/questions/7176726/how-can-i-pass-slash-and -other-url-sensitive-characters-to-a-wcf-rest-service) – 2016-02-04 18:48:48

+0

由於我無法控制被調用的外部服務,因此鏈接問題中的答案並非此問題的有效答案,因此更改服務合同中的uritemplate是不可能的。我修改了我的問題以反映這個約束。 – Stif 2016-03-12 16:53:16

回答

0

隨着大量的試驗和錯誤,我發現了一個非常醜陋,完全不合邏輯的解決方案,我的問題。但仍然...也許這篇文章可以幫助未來的人。 請注意,這個「解決方案」適用於.NET 4.5。我不保證它會爲你工作。

的問題歸結爲:

  • 這是不可能的(據我所知)把一個轉義正斜槓在烏里在.NET
  • 與外部服務(RabbitMQ的)通信我真的需要能夠認沽%2F(即正斜槓)在我的請求URL

下後把我的「正確」方向:How to stop System.Uri un-escaping forward slash characters

我試着在後提出的解決方案,但是......無濟於事

然後很多咒罵後,谷歌搜索,逆向工程等我想出了下面的一段代碼:

/// <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) 
    { 

    } 
} 

所以基本上我創建了一個自定義的EndpointBehavior,它使用反射向UriParser中的私有變量添加一個枚舉標誌。這顯然可以防止我的請求中逃脫的正斜槓。頭部。讓你不被轉義。

+0

它仍然可以避開字符。看到鏈接的答案。 – 2016-02-16 18:31:15