WCF RestFul例子

这里没有理论上的东西,仅仅是做下记录。我这个例子偷懒下了,直接在VS2008里面建了个WCF服务应用程序

一、接口,用WebGet的时候需要添加命名空间:System.ServiceModel;System.ServiceModel.Web;


[ServiceContract]
public interface IEmployeeService
{
[WebGet(UriTemplate = "employees", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
List<Employee> GetAll();

[WebGet(UriTemplate = "employees/{id}", ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Employee GetById(string id);

[WebInvoke(Method = "POST", UriTemplate = "add", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
void Add(Employee employee);

[WebInvoke(Method = "PUT", UriTemplate = "edit", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
void Edit(Employee employee);

[WebInvoke(Method = "DELETE", UriTemplate = "delete/{id}")]
[OperationContract]
void Delete(string id);
}

二、实体类


[DataContract]
public class Employee
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}

三、接口实现类


[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class EmployeeService : IEmployeeService
{
public List<Employee> Employees { get; set; }
public EmployeeService()
{
Employees = new List<Employee>
{
new Employee{ Id=1, Name="jack",Description="this is jack"},
new Employee{ Id=2, Name="tom",Description="this is tom"},
new Employee{ Id=3, Name="paul",Description="this is paul"}
};
}
#region IEmployeeService Members

public List<Employee> GetAll()
{
return Employees;
}

public Employee GetById(string id)
{
return Employees.FirstOrDefault(e => e.Id == int.Parse(id));
}

public void Add(Employee employee)
{
Employees.Add(employee);
}

public void Edit(Employee employee)
{
var entity = Employees.FirstOrDefault(e => e.Id == employee.Id);
entity.Name = employee.Name;
entity.Description = employee.Description;
}

public void Delete(string id)
{
Employees.RemoveAll(e => e.Id == int.Parse(id));
}

#endregion
}

四、配置文件,

 binding="webHttpBinding"  绑定方式一定要用webHttpBinding


<system.serviceModel>
<services>
<service behaviorConfiguration="WCFRestfulSample.EmployeeServiceBehavior" name="WCFRestfulSample.EmployeeService">
<endpoint address="" binding="webHttpBinding" contract="WCFRestfulSample.IEmployeeService" behaviorConfiguration="WCFRestfulSample.RestfulBehavior">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WCFRestfulSample.RestfulBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WCFRestfulSample.EmployeeServiceBehavior">
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--<bindings>
<webHttpBinding>
<binding name="defaultRest" >
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>-->
</system.serviceModel>

五、调用过程


const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
const string sContentType = "application/json";
static void Main(string[] args)
{
Add();
Console.ReadKey();
}
static void Select()
{
HttpWebRequest request = WebRequest.Create("http://localhost:32582/EmployeeService.svc/employees") as HttpWebRequest;
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
string result = string.Empty;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
result = reader.ReadToEnd();
}
}
Console.WriteLine(result);
}

static void Add()
{
string url = "http://localhost:32582/EmployeeService.svc/add";
HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
httpRequest.UserAgent = sUserAgent;
httpRequest.ContentType = sContentType;
httpRequest.Method = "POST";

//一定要先序列化然后在写入流
byte[] data = GetPostData();

httpRequest.ContentLength = data.Length;
using (Stream requestStream = httpRequest.GetRequestStream())
requestStream.Write(data, 0, data.Length);
using (var responseStream = httpRequest.GetResponse().GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
{
var result = responseReader.ReadToEnd();
Console.WriteLine("post return result:{0}", result);
}
}
}

static byte[] GetPostData()
{
var employee = new Employee()
{
Id = 98,
Name = "123sdf3",
Description = "this is my test..."
};
var json = ToJson(employee);
Console.WriteLine(json);
return Encoding.UTF8.GetBytes(json);
}
static string ToJson(object item)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());

using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, item);

StringBuilder sb = new StringBuilder();

sb.Append(Encoding.UTF8.GetString(ms.ToArray()));

return sb.ToString();

}

}
[DataContract]
public class Employee
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}

WCF RestFul例子

时间: 2024-08-30 01:56:12

WCF RestFul例子的相关文章

Linux学习日记-WCF RestFul的部署(三)

一.关于WCF 的部署 默认的wshttp风格的wcf是很容易部署上去的,但是这里给个建议尽量不要使用WCF的配置文件去部署尽管 我们都已经很熟悉了,在使用配置文件你会发现各种蛋疼的问题. 二.WCF Restful的部署 以下是简单的目录: 最主要的是主机的代码: 注: 一定要用代码,而不用配置文件 否则帮助页.默认返回格式什么的以配置就报异常 接口IService 类 using System; using System.Runtime.Serialization; using System

Wcf Restful Service服务搭建

目的 使用Wcf(C#)搭建一个Restful Service 背景 最近接到一个项目,客户要求使用Restful 方式接收到数据,并对数据提供对数据的统计显示功能,简单是简单,但必须要使用Restful方式,客户端传递数据就必须使用Rest ful的格式的url,提交方式为Post. 其实在之前的公司里边就开发过一个restful服务,但只记得自己使用的wcf,而今已经忘记的差不多了,还以为只是简单的搭建一个wcf就可以,今天起初就创建了一个wcf项目,发现wcf项目http://localh

wcf Restful编程五

Wcf rest编程 Restful 一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制.(关于这种编程风格大家可以百度下) Wcf 前面已经讲过,但自己书中不会创建一个restful风格的服务,最近看到一份外文博客分享给大家,这里这是创建,具体原理,我能懂了再分享个大家. Step1 新建wcf服务应用程序 Step2 添加新建项 Step3修改 修改接口 [Servic

[转]WCF RESTful service and WebGrid in ASP.NET MVC 5

使用WebClient调用WCF服务 流程:从View获取实体类-->序列化-->写入内存流中-->传给远端的WCF服务 Get.POST.PUT.DELETE using (WebClient wc = new WebClient()) { MemoryStream ms = new MemoryStream(); DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(

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.接口契约 1 using System; 2 using System.Colle

WCF的例子

Demo的 "Service端"以本机IIS为宿主,"Client端"以WebForm项目为例. 1.新建项目:WCF>WCF Service Application: 2.删除默认文件IService.cs与Service.svc.并分别创建增.删.改.查"Add.svc"."Save.svc"."Remove.svc"."Get.svc,Search.svc",分别对应4个功能

[WCF] Restful 自定义宿主

IPersonRetriever: /* * 由SharpDevelop创建. * 用户: Administrator * 日期: 2017/6/2 * 时间: 22:13 * * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件 */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceMod

UE4 WCF RestFul 服务器 读取JSON 数据并解析 简单实例

bool UWgtCpp_BaseMain::Http_readSortList() { auto temp_request = UNetAPI::createRequst(TEXT("http://localhost:59754/StudentService.svc/GetStudentList"), TEXT("GET")); temp_request->OnProcessRequestComplete().BindUObject(this, &U

Service Station - An Introduction To RESTful Services With WCF

Learning about REST An Abstract Example Why Should You Care about REST? WCF and REST WebGetAttribute and WebInvokeAttribute UriTemplate and UriTemplateTable WebHttpBinding and WebHttpBehavior WebServiceHost and WebServiceHostFactory Using the Example