开发者

Restful WCF bad request error

开发者 https://www.devze.com 2023-03-14 00:00 出处:网络
I have a simple resftul wcf service. The .svc file looks like this <%@ ServiceHost Service=\"NameSpace.RestfulService\" Factory=\"System.ServiceModel.Activation.WebServiceHostFactory\" %>

I have a simple resftul wcf service. The .svc file looks like this

<%@ ServiceHost Service="NameSpace.RestfulService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

The interface method declaration

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "test2", RequestFormat =  WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        List<MyObj> Test2(MyObj test);

Method implementation

 public List<MyObj> Test2(MyObj test)
    {
        return new List<MyObj>() { new MyObj() { MyObjId = "1", RowVersion = 1 }, new MyObj() { MyObj= "2", RowVersion = 2 } };
    }

Method on a wpf client to call the service

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyObj));
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, new MyObj() { MyObjId = "A", RowVersion = 1 });
        string jason = Encoding.Default.GetString(ms.ToArray());

        //get a handle to the request stream to write data to it    
        WebRequest myRequest = WebRequest.Create("http://localhost/MyService.svc/test2");
        myRequest.Method = "POST";
        myRequest.ContentType = "application/jason; charset=utf-8";

        StreamWriter sw = new StreamWriter(myRequest.GetRequestStream());
        sw.Write(jason);
        sw.Close();

        //get a handle to the response stream from the server to read the response
        WebResponse myResponse = myRequest.GetResponse();
        DataContractJsonSerializer RecData = new DataContractJsonSerializer(typeof(List<MyObj&开发者_如何学Pythongt;));

        var result = (List<MyObj>)RecData.ReadObject(myResponse.GetResponseStream());

When I try to get the RequestStream "myRequest.GetRequestStream()" it says bad request error 400. Any idea what might be causing this error?

Thanks


Your content type is "application/jason; charset=utf-8". JSON's MIME-type is "application/json" (no 'a'). This is my likely why it 400's when you send the initial headers (which is done when you call GetRequestStream) because the WCF service doesn't recognize the content-type and immediately rejects the request.

0

精彩评论

暂无评论...
验证码 换一张
取 消