WCF创建RESTService
这篇博客将介绍在WCF中创建REST服务相关内容。首先先看一下的项目结构:
Contract,Service两个工程为类库工程,需要添加System.ServiceModel, System.ServiceModel.Web, System.Runtime.Serialization名称空间,代码如下:
User Class:
using System; using System.Runtime.Serialization; namespace Contract { [DataContract] public class User { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public DateTime Birthday { get; set; } [DataMember] public bool Gender { get; set; } [DataMember] public int Age { get; set; } } }
IUserService
using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Web; namespace Contract { [ServiceContract] public interface IUserService { [WebGet(UriTemplate="Api/Users",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] IEnumerable<User> GetAll(); [WebGet(UriTemplate="Api/Users/{id}",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] User Get(string id); [WebInvoke(UriTemplate="Api/Users/{id}",Method ="DELETE",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)] bool Delete(String id); [WebInvoke(UriTemplate ="Api/Users",Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] bool Add(User user); [WebInvoke(UriTemplate ="Api/Users",Method = "PUT",RequestFormat = WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)] bool Update(User user); } }
这个和以往普通的WCF服务不一样,在方法名上面的Attribute为WebGet/WebInvoke,请求的参数放置在UriTemplate中。
UserService
using Contract; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Web; namespace Service { public class UserService : IUserService { private List<User> _cache = new List<User>(); public UserService() { _cache.Add(new User() { Id = 1, Name = "王大锤", Age = 20, Birthday = new DateTime(2012, 12, 31), Gender = true}); _cache.Add(new User() { Id = 2, Name = "张全蛋", Age = 21, Birthday = new DateTime(2012, 12, 31), Gender = true }); _cache.Add(new User() { Id = 3, Name = "赵铁柱", Age = 23, Birthday = new DateTime(2012, 12, 31), Gender = true }); _cache.Add(new User() { Id = 4, Name = "小美", Age = 22, Birthday = new DateTime(2012, 12, 31), Gender = false }); } public bool Add(User user) { bool result = false; try { var first = _cache.FirstOrDefault(u => u.Id == user.Id); if(first == null) { _cache.Add(user); result = true; WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Created; } else { result = false; } } catch (Exception) { result = false; } return result; } public bool Delete(string id) { bool result = false; try { var first = _cache.FirstOrDefault(u=>u.Id.ToString() == id); if(first != null) { _cache.Remove(first); WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Created; result = true; } else { result = false; WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound; } } catch (Exception) { result = false; } return result; } public User Get(string id) { var target = _cache.FirstOrDefault(u => u.Id.ToString() == id); WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; return target; } public IEnumerable<User> GetAll() { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; return _cache; } public bool Update(User user) { bool result = false; var target = _cache.FirstOrDefault(u => u.Id == user.Id); if(target != null) { _cache.Remove(target); _cache.Add(target); WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; } else { WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound; } return result; } } }
模拟实现了一个CURD的REST服务。下面就可以对服务进行承载。介绍两种方式,
1. 控制台程序:
App.config:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <system.serviceModel> <services> <service name="Service.UserService"> <endpoint address="http://192.168.1.100/UserService" binding="webHttpBinding" contract="Contract.IUserService" /> </service> </services> </system.serviceModel> </configuration>
Program.cs
static void Main(string[] args) { using (WebServiceHost host = new WebServiceHost(typeof(UserService))) { host.Opened += delegate { Console.WriteLine("Service is opened."); }; host.Open(); Console.Read(); } }
运行服务,在浏览器中访问获取所有User的服务,
2. 在IIS中承载服务,
在Service工程下添加Web.config文件:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="Service.UserService"> <endpoint address="" binding="webHttpBinding" contract="Contract.IUserService" /> </service> </services> </system.serviceModel> </configuration>
这里address不需要指定,IIS会分配一个地址给服务。
新建UserService.svc文件,
<%@ ServiceHost Service="Service.UserService" Language="C#" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
将Service编译路径指向到Bin目录下。然后再IIS中新建一个Application指向Service所在目录即可,
在浏览器中访问结果如下:
获得了一组Json数据。
关于WCF的REST服务就先介绍到这里,后面的博客会介绍如何来Consume这个服务。
感谢您的阅读,代码点击这里下载。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。