【问题标题】:WCF Restful post Services returns BAD REQUEST(400)WCF Restful post Services 返回 BAD REQUEST(400)
【发布时间】:2013-04-30 13:28:11
【问题描述】:

我从几天开始尝试使用 wcf 宁静的服务,但它给了我不好的请求。请帮帮我。

这是我的配置文件

<system.serviceModel>

<bindings>
  <webHttpBinding>
    <binding name="state" allowCookies="true">
      <security mode="None"></security>

    </binding>
  </webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="ServiceBehaviour" name="RESTFUL_DEMO.Web.services.Calc">
    <endpoint address="" bindingConfiguration="state" binding="webHttpBinding" name="Http" contract="RESTFUL_DEMO.Web.services.ICalc"/>
    <endpoint address="abcd" binding="wsHttpBinding" name="wsHttp" contract="RESTFUL_DEMO.Web.services.ICalc"/>

    <endpoint address="mex" binding="mexHttpBinding" name="MEX" contract="IMetadataExchange"/>

  </service>
</services>

我的服务合约和数据合约接口如下。

[ServiceContract(SessionMode = SessionMode.Allowed)]
[XmlSerializerFormat]
public interface ICalc
{
    [OperationContract]
    [WebInvoke(UriTemplate = "dowork", Method = "POST", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
    int DoWork(Enroll a);
}


[DataContract]
public class Enroll
{
    public Enroll()
    {

    }
    public Enroll(string Avalue)
    {
        this.Avalue = Avalue;
    }
    [DataMember(IsRequired = true)]
    public string Avalue
    {
        get;
        set;
    }


}

我使用服务的代码如下

HttpWebRequest request = WebRequest.Create("http://localhost/RESTFUL_DEMO.Web/services/Calc.svc/dowork") as HttpWebRequest;
XmlDocument doc = new XmlDocument();
        doc.Load(@"d:\test.xml");
        string sXML = doc.InnerXml;
        request.ContentLength = sXML.Length;
        request.ContentType = "test/xml; charset=utf-8";
        var sw = new StreamWriter(request.GetRequestStream());
        sw.Write(sXML);
        sw.Close();
        WebResponse response = request.GetResponse();
        StreamReader stream = new StreamReader(response.GetResponseStream());
        String result = stream.ReadToEnd();

【问题讨论】:

  • request.ContentType = "test/xml; charset=utf-8"; 应该是 request.ContentType = "text/xml; charset=utf-8";
  • sXML.Length 可能与写入流的字节长度不同,如果它包含非 ascii 字符..

标签: c# xml wcf rest


【解决方案1】:

您在使用 Rest 服务时犯了一个小错误。您已将请求的 ContentType 指定到 test/xml; charset=utf-8 但它应该是 text/xml 或 application/xml。

request.ContentType = "text/xml; charset=utf-8";

或者应该是

request.ContentType = "application/xml";

【讨论】:

    【解决方案2】:

    就我而言,我在服务接口 IBookService.cs 中的方法如下所示

    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "/Book", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    IList<Book> UpdateBook(Book book);
    

    在我的客户中,我给了

    client.Headers[HttpRequestHeader.ContentType] = "text/xml";  
    

    而不是

    client.Headers[HttpRequestHeader.ContentType] = "text/json";
    

    这解决了我的问题。请参阅下面的完整解决方案

     private void btnUpdateBook_Click(object sender, EventArgs e)
        {
            try
            {
                using(WebClient client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "text/json";                   
                    Uri uri = new Uri(@"http://localhost:8085/BookService/Book");
    
                    Book updateBook = new Book() { Id = 3, Name = "UpdateBook Name 3", Price = 77.77f };
    
                    MemoryStream requestStream = new MemoryStream();
                    DataContractJsonSerializer requestSerializer = new DataContractJsonSerializer(typeof(Book));
                    requestSerializer.WriteObject(requestStream, updateBook);
    
                    client.UploadDataCompleted += OnUpdateBookCompleted;
                    client.UploadDataAsync(uri, "PUT",requestStream.ToArray());
                }
            }
            catch (Exception ex)
            {
    
            }
        }
    
        void OnUpdateBookCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            byte[] result = e.Result as byte[];
            MemoryStream responseStream = new MemoryStream(result);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IList<Book>));
            IList<Book> books = (IList<Book>)serializer.ReadObject(responseStream);
    
            bindingSource1.DataSource = books;
            dvBooks.DataSource = bindingSource1;
        }
    

    【讨论】:

      【解决方案3】:

      在 Visual Studio 实例中启动并运行服务,然后使用 Test Client 确保服务运行正常。

      打开一个新的 VS 实例并添加一个服务引用,它将为您构建客户端代码,然后使用此客户端调用服务。

      【讨论】:

      猜你喜欢
      • 2013-04-16
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多