通过GET请求和响应将对象传递给WCF服务
本文关键字:WCF 服务 对象 GET 请求 求和 响应 通过 | 更新日期: 2023-09-27 18:00:11
我对WCF服务有点陌生。在我目前的工作中,我已经开发了一个helloworld Restful WCF服务。以下是我的RESTful web服务的代码。
RESTful服务合同如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace RestfulWCFService
{
[ServiceContract]
public interface IRestfulTestService
{
[OperationContract]
[WebInvoke(Method="GET", ResponseFormat= WebMessageFormat.Xml, UriTemplate="xml/{name}")]
string SayHelloXml(string name);
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "json/{name}")]
string SayHelloJson(string name);
}
}
接口实现如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace RestfulWCFService
{
public class RestfulTestService : IRestfulTestService
{
string IRestfulTestService.SayHelloXml(string name)
{
return "Hello " + name;
}
string IRestfulTestService.SayHelloJson(string name)
{
return "Hello " + name;
}
}
}
我已经在IIS上部署了此服务,现在我正在使用以下URL访问此web服务。
http://localhost/RestfulWCFService/RestfulTestService.svc/xml/pankesh
Web服务正在向我返回以下数据。
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello pankesh</string>
现在,我的问题是,在上面的Web服务上,我正在传递一个简单的数据类型,即STRING。现在,我的要求是通过REST请求传递一个复杂的自定义对象。你能告诉我吗?在上面的场景中,我如何通过REST请求传递自定义对象?
web.config
文件的内容如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<services>
<service name="RestfulWCFService.RestfulTestService">
<endpoint behaviorConfiguration="WebBehavior" binding="webHttpBinding" bindingConfiguration="" contract="RestfulWCFService.IRestfulTestService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
- 将对象序列化为流
- 作为流传递到服务
- 反序列化为数据合约
使用内存流进行序列化/反序列化