ERROR 400 - >来自客户端的错误请求

时间:2022-09-15 12:58:54

I'm new to WCF.I'm trying to call WCF from my aspx page to post xml and return json.My service works well but I'm getting an error of "The remote server returned an error: (400) Bad Request".Maybe WCF's config file gives such a error response to me.I tried lot but confusion only comes me..help me in code guys please.. And my client side code is

我是WCF的新手。我试图从我的aspx页面调用WCF发布xml并返回json.My服务运行良好但是我收到错误“远程服务器返回错误:(400)错误请求“.Maybe WCF的配置文件给了我这样的错误响应。我尝试了很多,但只是让我感到困惑..请帮我代码中的人..我的客户端代码是

string SampleXml = @"<parent>" +
               "<child>" +
                  "<username>username</username>" +
                    "<password>password</password>" +
                   "</child>" +
                "</parent>";
        //ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = SampleXml.ToString();
        byte[] data = Encoding.UTF8.GetBytes(postData); 
        string url = "http://localhost:52573/Service1.svc/postjson/";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "applicatoin/xml;charset=utf-8";
        //request.Accept = "application/json";
        request.ContentLength = data.Length;
        String test = String.Empty;
        Stream newStream = request.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            test = reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
        }
        Response.Write(test);

And WCF's Web.config file code is

而WCF的Web.config文件代码是

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<authorization>
        <allow users="?" />
</authorization>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
    <identity impersonate="false" />
</system.web>
<system.serviceModel>
<services>
  <service name="JsonandXmlService.Service1"    behaviorConfiguration="myServiceBehavior">
 <!--http://localhost:52573/Service1.svc/postjson/-->
    <endpoint name="myServiceBehavior" address="" binding="webHttpBinding"  contract="JsonandXmlService.IService1" behaviorConfiguration="webHttp">
    </endpoint>
    <endpoint name="mexHttpBinding" address="mex" binding="webHttpBinding" contract="IMetadataExchange" behaviorConfiguration="webHttp" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="myServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
    <behavior>
      <!--<!– To avoid disclosing metadata information, 
             set the value below to false and remove the metadata endpoint 
             above before deployment –>-->
      <serviceMetadata httpGetEnabled="true" />
      <!--<!– To receive exception details in faults for debugging purposes, 
             set the value below to true. Set to false before deployment 
             to avoid disclosing exception information –>-->
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="webHttp">
      <webHttp />
    </behavior>
  </endpointBehaviors>
</behaviors>

<protocolMapping>
    <add binding="webHttpBinding" scheme="https" />

</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="false" />

<directoryBrowse enabled="true" />
</system.webServer>

</configuration>

And my service file is here

我的服务文件就在这里

       public string postjson(string streamdata)
       {
        return new JavaScriptSerializer().Serialize(streamdata);          
       }

And interface is

接口是

 [OperationContract]
    [WebInvoke(UriTemplate = "postjson",Method="POST",RequestFormat=WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)]
    string postjson(string streamdata);

1 个解决方案

#1


0  

After a long time of struggle output came here..I didn't change any code in web.config of WCF.Here my Client side codes is

经过长时间的奋斗输出来到这里..我没有更改WCF的web.config中的任何代码。这是我的客户端代码是

 protected void Page_Load(object sender, EventArgs e)
    {

        // Restful service URL
        string url = "http://localhost:52573/Service1.svc/postjson";
        // declare ascii encoding
        ASCIIEncoding encoding = new ASCIIEncoding();
        string strResult = string.Empty;
        // sample xml sent to Service & this data is sent in POST
        string SampleXml = @"<parent>" +
               "<child>" +
                  "<username>username</username>" +
                    "<password>password</password>" +
                   "</child>" +
                "</parent>";
        string postData = SampleXml.ToString();
        // convert xmlstring to byte using ascii encoding
        byte[] data = encoding.GetBytes(postData);
        // declare httpwebrequet wrt url defined above
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);

        // set method as post
        webrequest.Method = "POST";
        // set content type
        //webrequest.Accept = "application/xml;q=0.8";
        //webrequest.ContentType = "application/xml;charset=utf-8";
        webrequest.ContentType = "application/x-www-form-urlencoded";
        // set content length
        webrequest.ContentLength = data.Length;
        // get stream data out of webrequest object
        Stream newStream = webrequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        // declare & read response from service
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

        // set utf8 encoding
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        // read response stream from response object
        StreamReader loResponseStream =
            new StreamReader(webresponse.GetResponseStream(), enc);
        // read string from stream data
        strResult = loResponseStream.ReadToEnd();
        // close the stream object
        loResponseStream.Close();
        // close the response object
        webresponse.Close();
        // below steps remove unwanted data from response string
        Response.Write(strResult);

    }

And my service implementation code is

我的服务实现代码是

     public string postjson(Stream streamdata)
    {
        StreamReader reader = new StreamReader(streamdata);
        string xmlString = reader.ReadToEnd();
        string returnValue = new JavaScriptSerializer().Serialize(xmlString);
        return returnValue.ToString();
    }

This is what i did guys...And I cleared recent files too...

这就是我做过的人......我也清除了最近的文件......

#1


0  

After a long time of struggle output came here..I didn't change any code in web.config of WCF.Here my Client side codes is

经过长时间的奋斗输出来到这里..我没有更改WCF的web.config中的任何代码。这是我的客户端代码是

 protected void Page_Load(object sender, EventArgs e)
    {

        // Restful service URL
        string url = "http://localhost:52573/Service1.svc/postjson";
        // declare ascii encoding
        ASCIIEncoding encoding = new ASCIIEncoding();
        string strResult = string.Empty;
        // sample xml sent to Service & this data is sent in POST
        string SampleXml = @"<parent>" +
               "<child>" +
                  "<username>username</username>" +
                    "<password>password</password>" +
                   "</child>" +
                "</parent>";
        string postData = SampleXml.ToString();
        // convert xmlstring to byte using ascii encoding
        byte[] data = encoding.GetBytes(postData);
        // declare httpwebrequet wrt url defined above
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);

        // set method as post
        webrequest.Method = "POST";
        // set content type
        //webrequest.Accept = "application/xml;q=0.8";
        //webrequest.ContentType = "application/xml;charset=utf-8";
        webrequest.ContentType = "application/x-www-form-urlencoded";
        // set content length
        webrequest.ContentLength = data.Length;
        // get stream data out of webrequest object
        Stream newStream = webrequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        // declare & read response from service
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

        // set utf8 encoding
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        // read response stream from response object
        StreamReader loResponseStream =
            new StreamReader(webresponse.GetResponseStream(), enc);
        // read string from stream data
        strResult = loResponseStream.ReadToEnd();
        // close the stream object
        loResponseStream.Close();
        // close the response object
        webresponse.Close();
        // below steps remove unwanted data from response string
        Response.Write(strResult);

    }

And my service implementation code is

我的服务实现代码是

     public string postjson(Stream streamdata)
    {
        StreamReader reader = new StreamReader(streamdata);
        string xmlString = reader.ReadToEnd();
        string returnValue = new JavaScriptSerializer().Serialize(xmlString);
        return returnValue.ToString();
    }

This is what i did guys...And I cleared recent files too...

这就是我做过的人......我也清除了最近的文件......