WCF Restful 服务 Get/Post请求

时间:2023-03-10 02:34:41
WCF Restful 服务 Get/Post请求

Restful  Get方式请求:

Restful服务 Get请求方式:http://localhost:10718/Service1.svc/Get/A/B/C

http://localhost:10718/Service1.svc 服务地址;Get 方法名;A,B,C分别为三个String参数的值。

请求所得数据将在页面显示如图:

1.返回值得类型会自行序列化成XML显示在页面

WCF Restful 服务 Get/Post请求

2.

http://localhost:10718/Service1.vsc/Get?StrA=A&StrB=B&StrC=C

代码实现:

简单示例:一个查询方法,获取三个参数,并将得到的参数显示到页面

1.接口契约

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text; namespace WcfService1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
       //UriTemplate = "Get?StrA={StrA}&StrB={StrB}&StrC={StrC}",
[WebGet(UriTemplate = "Get/{StrA}/{StrB}/{StrC}",
BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)]
string GetData(string StrA,string StrB,string StrC);
} }

2.接口服务

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text; namespace WcfService1
{
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class Service1 : IService1
{
public string GetData(string StrA, string StrB, string StrC)
{
return string.Format("You entered: A:{0},B:{1},C:{2}", StrA, StrB, StrC);
}
}
}

3. 配置文件

 <?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service behaviorConfiguration="GetPostBehavior" name="WcfService1.Service1">
<endpoint address="" behaviorConfiguration="GetPostEndBehaviors" binding="webHttpBinding"
contract="WcfService1.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://127.0.0.1:80/Service" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="GetPostServiceBinding">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="GetPostEndBehaviors">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="GetPostBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior>
<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
<serviceMetadata httpGetEnabled="true"/>
<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

Restful  Post方式请求: