0

我第一次尝试实现 Restful WCF 服务,但无法将其发布到我的对象 :( 它在客户端代码中崩溃(见下文)。有什么解决方法??谢谢

部分 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();
        }

服务1.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
}
4

2 回答 2

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 的服务是必要的(尽管在这个服务上可能是错误的)。

于 2012-07-26T13:47:39.153 回答
0

非常感谢,花了几天之后,现在我可以使用以下代码得到正确的响应:

 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();
于 2019-01-14T15:57:06.947 回答