错误400 - > WCF从客户方错误的请求 [英] ERROR 400-->wcf bad request from clientside

查看:208
本文介绍了错误400 - > WCF从客户方错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来WCF.I'm试图调用WCF从我的aspx页面发布XML并返回json.My服务工作得很好,但我得到的错误远程服务器返回错误:(400 )错误的请求。也许WCF的配置文件中给出了这样的错误回应我。我尝试了很多,但困惑只配备me..help我code家伙请..
而我的客户端code是

 字符串SampleXml = @<母体GT; +
               <儿童>中+
                  <用户名>用户名< /用户名> +
                    <密码和GT;密码和LT; /密码>中+
                   < /儿童>中+
                &所述; /亲>中;
        // ASCIIEncoding编码=新ASCIIEncoding();
        字符串POSTDATA = SampleXml.ToString();
        字节[]数据= Encoding.UTF8.GetBytes(POSTDATA);
        字符串的URL =HTTP://本地主机:52573 / Service1.svc / postjson /;
        HttpWebRequest的要求=(HttpWebRequest的)HttpWebRequest.Create(URL);
        request.Method =POST;
        request.ContentType =applicatoin / xml的;字符集= UTF-8;
        //request.Accept =应用/ JSON;
        request.ContentLength = data.Length;
        字符串测试=的String.Empty;
        方通流= request.GetRequestStream();
        newStream.Write(数据,0,data.Length);
        newStream.Close();
        使用(HttpWebResponse响应=(HttpWebResponse)request.GetResponse())
        {
            流数据流= response.GetResponseStream();
            StreamReader的读者=新的StreamReader(数据流);
            测试= reader.ReadToEnd();
            reader.Close();
            dataStream.Close();
        }
        回复于(试验);

和WCF的Web.config文件code是

 <?XML版本=1.0编码=UTF-8&GT?;
<结构>
<&的appSettings GT;
<添加键=ASPNET:UseTaskFriendlySynchronizationContextVALUE =真/>
< /的appSettings>
<&的System.Web GT;
<授权>
        <让用户=? />
< /授权>
<编译调试=真targetFramework =4.5/>
<的httpRuntime targetFramework =4.5/>
    <身份冒充=FALSE/>
< /system.web>
< system.serviceModel>
<服务和GT;
  <服务名称=JsonandXmlService.Service1behaviorConfiguration =myServiceBehavior>
 < --http://本地主机:52573 / Service1.svc / postjson / - >
    <端点名称=myServiceBehavior地址=绑定=的WebHttpBinding合同=JsonandXmlService.IService1behaviorConfiguration =webHttp>
    < /端点>
    <端点名称=mexHttpBinding地址=MEX绑定=的WebHttpBinding合同=IMetadataExchange接口behaviorConfiguration =webHttp/>
  < /服务>
< /服务>
<&行为GT;
  < serviceBehaviors>
    <行为NAME =myServiceBehavior>
      < serviceMetadata httpGetEnabled =真/>
      < serviceDebug includeExceptionDetailInFaults =真/>
    < /行为>
    <&行为GT;
      <! - <!€,以避免泄露的元数据信息,
             设定值以下为false并删除元数据终结
             上述部署之前€> - >
      < serviceMetadata httpGetEnabled =真/>
      <! - <!€要接收故障异​​常详细信息以进行调试,
             下面设置为true值。设置为false部署之前
             避免公开了一种€异常信息> - >
      < serviceDebug includeExceptionDetailInFaults =真/>
    < /行为>
  < / serviceBehaviors>
  < endpointBehaviors>
    <行为NAME =webHttp>
      < webHttp />
    < /行为>
  < / endpointBehaviors>
< /行为>< protocolMapping>
    <添加绑定=的WebHttpBinding计划=HTTPS/>< / protocolMapping>
< serviceHostingEnvironment aspNetCompatibilityEnabled =真multipleSiteBindingsEnabled =真/>
< /system.serviceModel>
< system.webServer>
<模块runAllManagedModulesForAllRequests =FALSE/>< directoryBrowse启用=真/>
< /system.webServer>< /结构>

和我的服务文件是在这里

 公共字符串postjson(字符串streamdata)
       {
        返回新的JavaScriptSerializer()序列化(streamdata)。
       }

和界面

  [OperationContract的]
    [WebInvoke(UriTemplate =postjson,方法=POST,RequestFormat = WebMessageFormat.Xml,ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)
    字符串postjson(字符串streamdata);


解决方案

在奋斗输出的很长一段时间来here..I没有发生任何变化code在WCF.Here我的客户端$的web.config文件C $ cs为

 保护无效的Page_Load(对象发件人,EventArgs的发送)
    {        // RESTful服务网址
        字符串的URL =HTTP://本地主机:52573 / Service1.svc / postjson
        //声明ASCII编码
        ASCIIEncoding编码=新ASCIIEncoding();
        字符串strResult =的String.Empty;
        发送到服务与//示例XML;这个数据在POST发送
        字符串SampleXml = @<母体GT; +
               <儿童>中+
                  <用户名>用户名< /用户名> +
                    <密码和GT;密码和LT; /密码>中+
                   < /儿童>中+
                &所述; /亲>中;
        字符串POSTDATA = SampleXml.ToString();
        //转换的xmlString使用ASCII编码字节
        字节[]数据= encoding.GetBytes(POSTDATA);
        //声明httpwebrequet WRT网址上面定义
        HttpWebRequest的WebRequest的=(HttpWebRequest的)WebRequest.Create(URL);        //设置方法为post
        webrequest.Method =POST;
        //设置内容类型
        //webrequest.Accept =application / xml进行; Q = 0.8;
        //webrequest.ContentType =application / xml进行;字符集= UTF-8;
        webrequest.ContentType =应用/的X WWW的形式urlen codeD;
        //设置内容长度
        webrequest.ContentLength = data.Length;
        //获取数据流出来,WebRequest对象
        方通流= webrequest.GetRequestStream();
        newStream.Write(数据,0,data.Length);
        newStream.Close();
        //声明和放大器;阅读服务响应
        HttpWebResponse WebResponse类=(HttpWebResponse)webrequest.GetResponse();        //设置UTF8编码
        编码ENC = System.Text.Encoding.GetEncoding(UTF-8);
        //从响应对象读取响应流
        StreamReader的loResponseStream =
            新的StreamReader(webresponse.GetResponseStream(),ENC);
        //从流中读取数据串
        strResult = loResponseStream.ReadToEnd();
        //关闭流对象
        loResponseStream.Close();
        //关闭响应对象
        webresponse.Close();
        //下面的步骤从响应字符串中删除不需要的数据
        的Response.Write(strResult);    }

和我的服务实现code是

 公共字符串postjson(流streamdata)
    {
        StreamReader的读者=新的StreamReader(streamdata);
        字符串的xmlString = reader.ReadToEnd();
        字符串的returnValue =新的JavaScriptSerializer()序列化(的xmlString)。
        返回returnValue.ToString();
    }

这是我做的家伙...而且我也清除最近打开文件...

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

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

<?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);

解决方案

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

 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...

这篇关于错误400 - &GT; WCF从客户方错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆