构建WCF RESTful service示例
天来分享一下如何建立一个关于建立WCF RESTful service的示例, REST(Representational State Transfer)是一种轻量级的Web Service架构,操作比传统的基于Operation操作的WCF service和Web service更为简洁实用,可以完全通过HTTP协议实现,还可以通过缓存来提高相应速度,性能效率和易用性上都要优于SOAP协议,所以比较推荐使用RESTful service取代SOAP service。
REST架构遵循了CRUD原则,即四种行为:Create, Read, Update, Delete. 通过这四种行为完成一般的操作和处理,并且可以通过结合这些操作完成复杂的service结构。REST架构让我们可以更加深入的了解HTTP协议, 针对于协议的编程,更有利于开发出伸缩性强的应用。
REST将网络上的所有事物都抽象为资源,并通过连接器接口对资源进行CRUD的操作。
好,闲话少说,通过一个例子来说明RESTful service的构建和调用方式。
这个例子是关于图片的一个例子,说明我们怎样通过service来上传图片,和浏览图片,并且通过service将我们的local资源可以上载的网络中,节省空间。当然根据你的需要,可以把代码改变为自己的应用程序的逻辑代码。
为了证明这个service的可用性 我们需要建立两个project来完成这个项目,一个为Server,另一个为Client,Client端负责通过service与Service端交互,所以service应该部署在Server端的Web application中。
[本示例完整源码下载]
具体下载目录在 /2012年资料/7月/27日/构建WCF RESTful service示例/
创建PictureRESTService.cs类 并且通过下载Web API来创建这个service, 这里的Web API是微软开发的一套帮助我们创建和使用RESTful service的工具,大家可以在这里下载,并且引用在项目中,注意这些API有相互引用的地方所以建议大家在引用时候全部加入引用。
[最新的版本 WCF Web API Preview 5] http://wcf.codeplex.com/releases/view/73399
引用例子: using Microsoft.ApplicationServer.Http;
PictureRESTService.cs
- namespace CSWCFPhotoRatingSystem
- {
- /// <summary>
- /// The RESTful web service that used to handle image basic functions.
- /// </summary>
- [ServiceContract]
- [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
- [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall, Namespace="PictureService")]
- public class PictureRESTService
- {
- /// <summary>
- /// Images search service.
- /// </summary>
- /// <param name="image"></param>
- /// <returns></returns>
- [WebGet(UriTemplate="/{image}")]
- public HttpResponseMessage GetImages(string image)
- {
- var response = new HttpResponseMessage();
- Stream memory = new MemoryStream();
- memory = GetImageByName(image);
- memory.Position = 0;
- response.Content = new StreamContent(memory);
- response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
- return response;
- }
- /// <summary>
- /// Image adding service.
- /// </summary>
- /// <param name="message"></param>
- /// <param name="image"></param>
- [WebInvoke(UriTemplate = "/{image}", Method = "POST")]
- public void AddImages(HttpRequestMessage message,string image)
- {
- var directory = System.Web.HttpContext.Current.Server.MapPath("~/Images");
- var file = Path.Combine(directory, image);
- Stream stream = message.Content.ContentReadStream;
- FileStream fileStream = File.Create(System.Web.HttpContext.Current.Server.MapPath("~/Image/") + image);
- stream.CopyTo(fileStream);
- stream.Close();
- fileStream.Close();
- this.XmlFileAppend(image, System.Web.HttpContext.Current.Server.MapPath("~/Image/") + image);
- }
- /// <summary>
- /// Images information searching service.
- /// </summary>
- /// <returns></returns>
- [WebGet(UriTemplate="",ResponseFormat=WebMessageFormat.Json)]
- public List<string> GetImageList()
- {
- List<string> list = this.GetAllImages();
- if (list != null && list.Count != 0)
- {
- return list;
- }
- else
- {
- return null;
- }
- }
- /// <summary>
- /// Get specify image by image's Name property.
- /// </summary>
- /// <param name="image"></param>
- /// <returns></returns>
- public Stream GetImageByName(string image)
- {
- XDocument document = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Photo.xml"));
- var nodeList = from node in document.Descendants("Image")
- where node.Attribute("open").Value.ToString().Equals("1")
- select node;
- foreach (var node in nodeList)
- {
- if (node.Element("Name").Value.Equals(image))
- {
- FileStream fileStream = null;
- string physicUrl = node.Element("PhysicsUrl").Value;
- fileStream = File.Open(physicUrl, FileMode.Open);
- MemoryStream ms = new MemoryStream();
- fileStream.CopyTo(ms);
- return ms;
- }
- }
- return null;
- }
- /// <summary>
- /// Get all images' physics url string variable.
- /// </summary>
- /// <returns></returns>
- public List<string> GetAllImages()
- {
- List<string> list = new List<string>();
- XDocument document = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Photo.xml"));
- var nodeList = from node in document.Descendants("Image")
- where node.Attribute("open").Value.ToString().Equals("1")
- select node;
- foreach (var node in nodeList)
- {
- list.Add(node.Element("PhysicsUrl").Value);
- }
- return list;
- }
- /// <summary>
- /// Add XElement to xml file to record new images.
- /// </summary>
- /// <param name="fileName"></param>
- /// <param name="physicsUrl"></param>
- protected void XmlFileAppend(string fileName, string physicsUrl)
- {
- string xmlPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Photo.xml");
- XDocument document = XDocument.Load(xmlPath);
- XElement element = new XElement("Image", new XElement("Name", fileName), new XElement("PhysicsUrl", physicsUrl));
- element.Add(new XAttribute("open", "1"));
- document.Element("Root").Add(element);
- document.Save(xmlPath);
- }
- }