为什么远程服务器返回错误

为什么远程服务器返回错误

本文介绍了为什么远程服务器返回错误:(400)错误的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有我的第一次尝试在实施一个RESTful的WCF服务,但不能把它发布到我的对象:(
它崩溃的clientstuff code(见下文)。可能是什么?修复
谢谢

部分的web.config

 < system.serviceModel>
    <服务和GT;
      <服务名称=MyRest.Service1behaviorConfiguration =ServBehave>
        <! - 终点为REST - >
        <端点地址=XMLService绑定=的WebHttpBindingbehaviorConfiguration =restPoxBehavior合同=MyRest.IService1/>
      < /服务>
    < /服务>
    <&行为GT;
      < serviceBehaviors>
        <行为NAME =ServBehave>
          <! - 为了避免泄露的元数据信息,下面设置为false的价值和部署之前删除上面的元数据终结点 - >
          < serviceMetadata httpGetEnabled =真/>
          <! - 要接收故障中的异常细节进行调试,下面设置为true值。设置为false部署之前,以避免泄露异常信息 - >
          < serviceDebug includeExceptionDetailInFaults =FALSE/>
        < /行为>
      < / serviceBehaviors>
      < endpointBehaviors>
        <! - 行为的REST端点帮助enability - >
        <行为NAME =restPoxBehavior>
          < webHttp helpEnabled =真/>
        < /行为>
      < / endpointBehaviors>
    < /行为>
    < serviceHostingEnvironment aspNetCompatibilityEnabled =真multipleSiteBindingsEnabled =真/>
  < /system.serviceModel>

客户端code:

 公共字符串ClientStuff()
        {
            VAR的serviceUrl =HTTP://localhost/MyRest/Service1.svc/XMLService/
            VAR empserializer =新的DataContractSerializer(typeof运算(MyRest.Employee));
            VAR URL =新的URI(的serviceUrl +PostEmp);
            VAR请求=(HttpWebRequest的)WebRequest.Create(URL);
            request.Method =POST;
            request.ContentType =应用程序/ XML
            VAR EMP =新MyRest.Employee {DEPTNAME =买卖,EmpName =泰德,EMPNO = 11112};
            使用(VAR requeststream = request.GetRequestStream())
            {
                empserializer.WriteObject(requeststream,EMP);
            }
            VAR响应=(HttpWebResponse)request.GetResponse(); //这里崩溃在标题错误
            VAR状态code = response.Status code;
            返回状态code.ToString();
        }

service1.svc.cs

 公共BOOL PostEmp(员工员工)
        {
            //东西
            返回true;
        }

的ServiceContract

  [的ServiceContract]
公共接口IService1
{
    [OperationContract的]
    [WebInvoke(方法=POST,UriTemplate =/ PostEmp,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)
    布尔PostEmp(员工员工);    // TODO:添加您的业务运营在这里
}


解决方案

有几件事情你应该修正。第一个当然是使用正确的内容类型头的,有没有这样的东西应用程序/ XML

  request.ContentType =文/ XML;

和其他的,更重要的是要确保你所引用您的服务器和客户机完全相同的员工类,否则客户端数据契约序列化器将发射不同的命名空间中的XML使服务器崩溃。基本上,这员工类应该在你的服务器和客户端应用程序之间共享的类库中声明。

和的方式更容易地能够通过自己的未来,而不是在这里张贴问题,根本的:

 <&System.Diagnostics程序GT;
    <来源和GT;
        <信源名称=System.ServiceModel
                switchValue =信息,ActivityTracing
                propagateActivity =真正的>
            <&听众GT;
                <添加名称=的TraceListener
                     类型=System.Diagnostics.XmlWriterTraceListener
                     initializeData =C:\\登录\\ Traces.svclog/>
            < /听众>
        < /源>
    < /来源>
< /system.diagnostics>

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

向你解释

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

 < serviceHostingEnvironment aspNetCompatibilityEnabled =真multipleSiteBindingsEnabled =真/>

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

having my first crack at implementing a Restful WCF service but cant get it to Post my object :(It crashes in the clientstuff code (see below). What could be the fix??thanks

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

client code:

 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

[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
}
解决方案

There are a couple of things you should fix. The first one is of course to use the proper content type header, there's no such thing as application/XML:

request.ContentType = "text/xml";

and the other, and more important thing is to ensure that you are referencing the exactly same Employee class in your server and client, otherwise the client data contract serializer will emit a different namespace in the XML making the server crash. Basically this Employee class should be declared in a shared class library between your server and client application.

And by the way to more easily be able to debug this kind of problems by yourself in the future instead of posting questions here simply enable tracing on your service side:

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

and then use the built into the .NET SDK trace viewer (SvcTraceViewer.exe) to simply load the generated log file and everything will be shown and explained to you in with a GUI (that looks like coming from the 90s but does the job).

Ah and by the way you might need to disable ASP.NET compatibility by removing the following line from your web.config:

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

I am not 100% sure but IIRC this was necessary with REST enabled services (might be wrong though on this one).

这篇关于为什么远程服务器返回错误:(400)错误的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:15