在WebClient.OpenWrite上设置Content-Type标头会生成WebException

时间:2011-10-29 23:53:03

标签: wcf post webclient content-type webexception

我正在使用WebClient.OpenWrite来POST到.NET 4中的WCF HTTP Web服务。如果我在WebClient标头上设置了内容类型,那么当流是时,我最终会遇到WebException(400 - 错误请求)闭合。

var client = new WebClient();

// Setting ContentType generates a WebException on 400 - Bad Request when the stream is closed
//client.Headers[ HttpRequestHeader.ContentType ] = "application/json";

var stream = client.OpenWrite( "http://localhost:21159/Colors.svc/Color", "POST" );

var serializer = new DataContractJsonSerializer( typeof( ClientColor ) );
serializer.WriteObject( stream, color );
stream.Close();

服务界面如下所示:

[ServiceContract]
public interface IColors
{
  [WebInvoke( UriTemplate = "Color", Method = "POST" )]
  void ColorPost( Stream color );
}

如果我将Content-Type标头设置为“application / xxx”,则POST可正常工作。

当Content-Type为“application / json”时,为什么我得到WebException的任何想法?

0 个答案:

没有答案