在使用GET访问WCF rest服务时获得400个http错误请求

时间:2022-10-14 17:20:32

the Exact error is System.Net.WebException: The Remote server returned an Error: (400) Bad Request. at system.Net.HttpWebRequest.GetResponse()i have a WCF rest service hosted in IIS..I have created a simple WPF app with just a button..now i need to access the methods in my WCF service using get..

确切的错误是System.Net。WebException:远程服务器返回一个错误:(400)错误请求。在system.Net.HttpWebRequest.GetResponse()中,我有一个托管在IIS中的WCF rest服务。我用一个按钮创建了一个简单的WPF应用。现在我需要使用get访问WCF服务中的方法。

This is the code For WPF

这是WPF的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Runtime.Serialization;
using System.Xml;
namespace RestFulDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RestDemo_Click(object sender, RoutedEventArgs e)
        {
            string msg="";
            HttpWebResponse resp=null;
            //WebRequest my = WebRequest.Create(@"http://www.google.com");
            //MessageBox.Show(my.ToString());
            WebRequest myRequest = WebRequest.Create(@"http://localhost/REST/RestServicesSample.svc/XmlData/sad");
            MessageBox.Show(myRequest.ToString());
            //Provides response from a URI.
            myRequest.Method = "GET";
            myRequest.ContentType = @"text/xml; charset=utf-8";
            try
            {
                 resp=myRequest.GetResponse() as HttpWebResponse;
            }
            catch (WebException c)
            {
                MessageBox.Show(c.ToString());
            }

            if (resp.StatusCode == HttpStatusCode.OK)
            {
                XmlDocument myXMLDocument = new XmlDocument();
                XmlReader myXMLReader = new XmlTextReader(resp.GetResponseStream());
                myXMLDocument.Load(myXMLReader);
                msg= myXMLDocument.InnerText;
            }
            MessageBox.Show(msg);
        }
    }
}

why do i get an error in myRequest.GetResponse()..? this is my .svc.cs file

为什么在myRequest.GetResponse().. ..中会出现错误?这是我的svc。名cs文件

using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

namespace RestServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IRestServicesSample" in both code and config file together.
    [ServiceContract]
    public interface IRestServicesSample
    {
        [OperationContract]
        [WebGet]
        ////[WebInvoke(Method = "GET",
        ////    ResponseFormat = WebMessageFormat.Xml,
        ////    BodyStyle = WebMessageBodyStyle.Wrapped,
        ////    UriTemplate = "xml/{id}")]
       string XmlData(string id);
        //void DoWork();
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "json/{id}")]
        string JsonData(string id);
    }
}

---this is the web.config file

——这是网络。配置文件

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
      </webServices>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RestServices.RestServiceSample" behaviorConfiguration="ServiceBehaviour">
        <endpoint behaviorConfiguration="WebBehavior" binding="webHttpBinding" contract="RestServices.IRestServiceSample">
        </endpoint>
      </service>`enter code here`
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- 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="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp/>
        </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

1 个解决方案

#1


0  

For service configuration please take a look at: Can't connect to rest webservice through c# client

对于服务配置,请查看:不能通过c#客户端连接rest webservice。

This is a sample C# client making a GET request

这是一个c#客户端发出GET请求的示例

string url = "localhost:8080/MyService.svc/Submit/" + "helloWorld";
string strResult = string.Empty;

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "GET";

// set content type based on what your service is expecting
webrequest.ContentType = "application/xml";

//Gets the response
WebResponse response = webrequest.GetResponse();

//Writes the Response
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream);
string s = sr.ReadToEnd();
return s;

#1


0  

For service configuration please take a look at: Can't connect to rest webservice through c# client

对于服务配置,请查看:不能通过c#客户端连接rest webservice。

This is a sample C# client making a GET request

这是一个c#客户端发出GET请求的示例

string url = "localhost:8080/MyService.svc/Submit/" + "helloWorld";
string strResult = string.Empty;

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "GET";

// set content type based on what your service is expecting
webrequest.ContentType = "application/xml";

//Gets the response
WebResponse response = webrequest.GetResponse();

//Writes the Response
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream);
string s = sr.ReadToEnd();
return s;