WCF WebInvoke可以接受内容类型:text / plain?

我正在编写WCF REST服务以使用我的WCF REST服务接收AWS SNS通知消息。

但是,WCF REST仅支持XML和JSON,但由于传统原因,Amazon SNS使用Content-Type: text/plain; charset=UTF-8发布其通知Content-Type: text/plain; charset=UTF-8 根据亚马逊文档 , Content-Type: text/plain; charset=UTF-8标头:

 POST / HTTP/1.1 Content-Type: text/plain; charset=UTF-8 // ... { "Type" : "Notification", // ... "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&..." } 

当我使用像Amazon这样的“text / plain”内容类型调用我的服务时,会出现一个错误:

请求错误。

服务器遇到处理请求的错误。 exception消息是’传入消息具有意外的消息格式’Raw’。 该操作的预期消息格式是’Xml’; ‘Json的’。 这可能是因为尚未在绑定上配置WebContentTypeMapper。 有关更多详细信息,请参阅WebContentTypeMapper的文档。 请参阅服务器日志以获取更多详

我目前的代码:

 public interface MyServiceInterface { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/AmazonIPChanges")] Task AmazonIPChanges(SNSNotificationMessage data); } [DataContract] public class SNSNotificationMessage { [DataMember] public string Type { get; set; } // ... [DataMember] public string UnsubscribeURL { get; set; } } 

DataContract映射到Amazon SNS消息。 当我使用内容类型“application / json”执行POST时,此代码正常工作,但是如何让它接受Amazon的text / plain内容类型?

您可以通过创建和应用自定义WebContentTypeMapper来解决此问题,如错误消息所示。 它应该如下所示:

 namespace StackOverflow36216464 { public class RawContentTypeMapper : WebContentTypeMapper { public override WebContentFormat GetMessageFormatForContentType(string contentType) { switch (contentType.ToLowerInvariant()) { case "text/plain": case "application/json": return WebContentFormat.Json; case "application/xml": return WebContentFormat.Xml; default: return WebContentFormat.Default; } } } } 

这个解释了请求的内容类型,并返回适当的WebContentFormat枚举成员。

然后,您可以以自定义绑定的forms将其应用于您的服务:

                                 

相关部分是元素,其中配置了自定义映射器,以及应用它的servcices/service/endpoint/bindingConfiguration属性。