假设我想使用WCF调用一个外部的REST服务(这意味着我无法控制合同)。我有以下合同
[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路径参数?
发布于 2013-04-24 13:21:35
经过大量的尝试和错误,我找到了一个非常丑陋和完全不合逻辑的解决方案。但还是..。也许这篇文章能对未来的人有所帮助。请注意,在.NET 4.5中,这个“解决方案”对我有效。我不保证它会对你有用。
问题的关键在于:
下面的帖子让我走上了“正确”的方向:如何阻止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)
{
}
}因此,基本上,我正在创建一个自定义EndpointBehavior,它使用反射向UriParser中的私有变量添加枚举标志。这显然防止了我的request.Headers.To uri中的转义正斜杠不被转义。
https://stackoverflow.com/questions/16170442
复制相似问题