【发布时间】:2011-09-13 19:29:25
【问题描述】:
我正在为Menalto Gallery 3 编写一个.NET 客户端,它使用一个RESTful JSON API(请参阅API docs)。我决定为我的客户使用 WCF,它看起来可以大大简化我的工作,如果不是因为有一种方法需要 application/x-www-form-urlencoded 而不是 application/json 的 Content-Type。
我见过各种 hacks 从 WCF 发送 urlencoded 数据,例如 using a Stream parameter,它使我能够发送任意数据,但仍然需要 IClientMessageInspector 来设置 Content-Type:
internal class GalleryClientMessageInspector : IClientMessageInspector {
public object BeforeSendRequest(ref Message request, IClientChannel channel) {
HttpRequestMessageProperty httpRequestMessage =
getOrAddRequestMessageProperty(request);
if (/* this is the one API method using urlencoded data */) {
httpRequestMessage.Headers["Content-Type"] = "application/x-www-form-urlencoded";
}
}
// ...remaining IClientMessageInspector methods...
}
如您所见,在这种情况下我的问题是 IClientMessageInspector 不知道消息来自哪个方法(因此我无法查找 UrlEncoded 属性或告诉我使用 urlencoded 格式的内容本例)。
如何在 WCF 中添加对 urlencoded 消息的支持而不使用此类 hack?
理想情况下,我只想用一个属性装饰我的方法声明,并将一些检查器、编码器、格式化程序或其他任何东西挂接到 WCF 中,它们会找到这个属性并对方法的参数进行 urlencode,而不是将它们序列化为 JSON,例如。
[
OperationContract,
WebInvoke(UriTemplate = ""),
OverrideMessageFormat(CustomMessageFormat.UrlEncoded) // like this
]
string Login(string user, string password);
【问题讨论】:
标签: .net wcf json .net-4.0 urlencode