首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WCF UriTemplate UrlEncode

WCF UriTemplate UrlEncode
EN

Stack Overflow用户
提问于 2013-04-23 13:19:44
回答 1查看 2.6K关注 0票数 2

假设我想使用WCF调用一个外部的REST服务(这意味着我无法控制合同)。我有以下合同

代码语言:javascript
复制
[ServiceContract]
public interface ISomeRestApi
{
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "blablabla/{parameter1}/{parameter2}")]
    void PutSomething(string parameter1, string parameter2);
}

假设我的一个参数是正斜杠(/)

代码语言:javascript
复制
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路径参数?

EN

回答 1

Stack Overflow用户

发布于 2013-04-24 13:21:35

经过大量的尝试和错误,我找到了一个非常丑陋和完全不合逻辑的解决方案。但还是..。也许这篇文章能对未来的人有所帮助。请注意,在.NET 4.5中,这个“解决方案”对我有效。我不保证它会对你有用。

问题的关键在于:

  • 在.NET中将转义的正斜杠放入Uri是不可能的
  • 为了与外部服务(RabbitMQ)通信,我确实需要能够在请求Url中放置%2f (即正斜杠)

下面的帖子让我走上了“正确”的方向:如何阻止System.Uri未转义正斜杠字符

我试过了文章中提出的解决方案,但是.徒劳无功

然后,经过大量的咒骂、谷歌搜索、逆向工程等等之后,我想出了以下代码:

代码语言:javascript
复制
/// <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中的私有变量添加枚举标志。这显然防止了我的request.Headers.To uri中的转义正斜杠不被转义。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16170442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档