是否可以强制WCF REST端点接受Raw消息格式?

Jac*_*cob 3 .net vb.net rest wcf

我有一个包含SOAP和REST端点的Web服务.我必须接受来自客户端的请求,即我对我的REST端点没有任何控制权.目前客户端得到400响应,我服务器上的tracelog显示此错误:

The incoming message has an unexpected message format 'Raw'. 
The expected message formats for the operation are 'Xml', 'Json'. 
Run Code Online (Sandbox Code Playgroud)

我已经尝试了所有我能想到的WebContentTypeMapper,但似乎最终我每次都开始.来自客户端的请求似乎不是格式良好的XML或JSON,因此如果我尝试从WebContentTypeMapper强制XML或JSON类型,我最终会出现解析器错误.

所以我想我需要找出是否可以强制这个端点接受该消息.这应该很容易,对吧?...家伙?...对?

Ric*_*ett 8

如果您使操作采用流,那么您可以自己分析传入的数据并找出如何处理它.HTTP请求的ContentType应该告诉您流中的内容

例如,假设您有一项允许您上传图像的服务.您可能希望根据图像类型执行不同类型的图像处理.所以我们有一份服务合同如下:

[ServiceContract]
interface IImageProcessing
{
    [OperationContract]
    [WebInvoke(Method="POST", UriTemplate = "images")]
    void CreateImage(Stream stm);
}
Run Code Online (Sandbox Code Playgroud)

实现检查请求的Content类型并执行依赖于它的处理:

public void CreateImage(Stream stm)
{
    switch(WebOperationContext.Current.IncomingRequest.ContentType)
    {
      case "image/jpeg":
          // do jpeg processing on the stream
          break;

      case "image/gif":
          // do GIF processing on the stream
          break;

      case "image/png":
          // do PNG processing on the stream
          break;

      default:
          throw new WebFaultException(HttpStatusCode.UnsupportedMediaType);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果传入消息的Content-Type是text/xml或application/json,WCF将_still_尝试解码它,忽略您的Stream参数类型.唯一明显的方法是在消息编码器上为Endpoint实现WebContentTypeMapper绑定,将消息类型替换为Raw. (4认同)