使用 GET 访问 WCF 休息服务时出现 400 http 错误请求错误

Posted

技术标签:

【中文标题】使用 GET 访问 WCF 休息服务时出现 400 http 错误请求错误【英文标题】:Getting 400 http bad request error while accessing WCF rest service using GET 【发布时间】:2013-11-27 08:06:20 【问题描述】:

the Exact error is System.Net.WebException: The Remote server returned an Error: (400) Bad Request. at system.Net.HttpWebRequest.GetResponse()我有一个托管在 IIS 中的 WCF 休息服务..我创建了一个简单的 WPF 应用程序,只有一个按钮..现在我需要使用 get 访问我的 WCF 服务中的方法..

这是 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);
        
    

为什么在 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);
    

---这是web.config文件

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

【问题讨论】:

请记住在您的 OperationContract 中添加 RequestFormat。如果不是我认为的服务默认请求格式为 JSON 【参考方案1】:

服务配置请看:Can't connect to rest webservice through c# client

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

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;

【讨论】:

我尝试将 ContentType 设置为“application/xml”,我的配置与您提供的链接中提到的相同...在 IIS 上托管 WCF REST 服务是否可能存在问题? 发现了问题..问题是我的请求 url 与 uri 模板不匹配.. 太棒了!希望你会发现这很有用。我在学习 WCF 时花了很长时间来获得一个 REST 服务的工作示例以及一个客户端成功地向它发布或获取数据。 无论如何谢谢...是的..这需要很多时间 @CharlieOuYang :我为此创建了一个帖子。我希望这可能会有所帮助。 winzikha.blogspot.com/2015/07/…

以上是关于使用 GET 访问 WCF 休息服务时出现 400 http 错误请求错误的主要内容,如果未能解决你的问题,请参考以下文章

尝试使用 XHR 联系 WCF 服务时出现 400 错误请求

尝试 GET 时出现 WCF REST 404

在 wcf rest 中发送 xml 请求时出现错误请求 400

从 Windows 应用程序访问托管在 IIS 上的 WCF 服务时出现问题

调用 Sitefinity WCF Web 服务时出现错误 401

在我的 Web 应用程序引用的类库中访问 wcf 数据服务时出现问题