3

WebClient.OpenWrite を使用して、.NET 4 の WCF HTTP Web サービスに POST します。WebClient ヘッダーにコンテンツ タイプを設定すると、ストリームが閉じられたときに WebException (400 - Bad Request) が発生します。

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 が発生する理由はありますか?

4

0 に答える 0