【问题标题】:Using x-www-form-urlencoded Content-Type in WCF在 WCF 中使用 x-www-form-urlencoded Content-Type
【发布时间】: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


    【解决方案1】:

    默认情况下不支持表单帖子(不支持内容类型),但 WCF 示例提供了两个与此主题相关的示例:

    • 自定义 WebContentTypeMapper 以添加对新内容类型的支持
    • Form Post - HTML 帖子的示例,但您可以检查它的工作原理并为 JSON 制作自己的

    还有WCFRestContrib 项目支持表单发布。旧的Rest Starter Kit 也支持表单帖子,但 REST Starter Kit 从未通过社区预览。最后一个即将到来的Web-API(它将成为未来 WCF 版本的一部分)也支持使用表单。目前 Web-API 可作为 CTP1 使用。

    【讨论】:

    • 我已经查看了这些项目,并自己做了一些工作以使 WCF 支持自定义内容类型(通过包装原始内容类型的 IClientMessageFormatter),但在研究如何自动对我的当看起来我必须克隆 BodyWriteMessage 类和许多其他东西时,我放弃了消息。
    • 感谢您提供 Web-API 链接,当 Web-API 发布时,我将再次尝试我的项目!
    猜你喜欢
    • 2019-02-04
    • 2013-11-10
    • 1970-01-01
    • 2017-09-22
    • 2017-07-19
    • 2017-09-26
    • 2017-08-29
    • 2019-05-24
    • 2018-12-27
    相关资源
    最近更新 更多