为什么远程服务器返回错误:(400)错误的请求?(Why The remote server ret

2019-09-20 06:21发布

有我的第一次尝试在实现RESTful WCF服务,但不能得到它后我的对象:(这崩溃的clientstuff代码(见下文)。这可能是什么?修复感谢

部分的web.config

<system.serviceModel>
    <services>
      <service name="MyRest.Service1" behaviorConfiguration="ServBehave">
        <!--Endpoint for REST-->
        <endpoint address="XMLService" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="MyRest.IService1" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServBehave">
          <!-- 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 for the REST endpoint for Help enability-->
        <behavior name="restPoxBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

客户代码:

 public string ClientStuff()
        {
            var ServiceUrl = "http://localhost/MyRest/Service1.svc/XMLService/";
            var empserializer = new DataContractSerializer(typeof(MyRest.Employee));
            var url = new Uri(ServiceUrl + "PostEmp");
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/XML";
            var emp = new MyRest.Employee { DeptName = "sale", EmpName = "ted", EmpNo = 11112 };
            using (var requeststream = request.GetRequestStream())
            {
                empserializer.WriteObject(requeststream, emp);
            }
            var response = (HttpWebResponse)request.GetResponse();// crashes here with error in title
            var statuscode = response.StatusCode;
            return statuscode.ToString();
        }

service1.svc.cs

 public bool PostEmp(Employee employee)
        {
            //something
            return true;
        }

服务合同

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/PostEmp", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    bool PostEmp(Employee employee);

    // TODO: Add your service operations here
}

Answer 1:

有一对夫妇的事情,你应该可以解决。 第一个当然是使用正确的内容类型头,有因为没有这样的东西application/XML

request.ContentType = "text/xml";

而另一方面,也是更重要的一点是要确保你所引用的完全相同Employee在你的服务器和客户端类,否则客户端的数据串行合同将在XML使服务器崩溃发出不同的命名空间。 基本上这个Employee类应该在您的服务器和客户端应用程序之间共享的类库中声明。

顺便说一句更容易能够通过自己在未来的调试这样的问题,而不是简单地在这里张贴问题的启用跟踪你的服务端:

<system.diagnostics>
    <sources>
        <source name="System.ServiceModel" 
                switchValue="Information, ActivityTracing"
                propagateActivity="true">
            <listeners>
                <add name="traceListener" 
                     type="System.Diagnostics.XmlWriterTraceListener" 
                     initializeData= "c:\log\Traces.svclog" />
            </listeners>
        </source>
    </sources>
</system.diagnostics>

然后使用内置在.NET SDK跟踪查看器( SvcTraceViewer.exe )简单地加载生成的日志文件,一切都将被显示,并与一个GUI给你解释(看起来像从上世纪90年代来,但做这项工作) 。

阿和方式可能需要通过从你的web.config以下行来禁用ASP.NET兼容性:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

我不是100%肯定,但IIRC,这是必要的REST启用服务(可能是错误的,虽然在这一个)。



Answer 2:

非常感谢,花费几天后,现在我可以使用下面的代码来获取正确的回应:

 var ServiceUrl = "http://localhost/MyRest/Service1.svc/XMLService/";
            var empserializer = new DataContractSerializer(typeof(MyRest.Employee));
            var url = new Uri(ServiceUrl + "PostEmp");
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/XML";
            var emp = new MyRest.Employee { DeptName = "sale", EmpName = "ted", EmpNo = 11112 };
            using (var requeststream = request.GetRequestStream())
            {
                empserializer.WriteObject(requeststream, emp);
            }
            var response = (HttpWebResponse)request.GetResponse();// crashes here with error in title
            var statuscode = response.StatusCode;
            return statuscode.ToString();

下面的代码行此追加的添加:

 StreamReader reader = new StreamReader(response.GetResponseStream());
 string ResponseMessage = reader.ReadToEnd();


文章来源: Why The remote server returned an error: (400) Bad Request.?