介绍了REST WCF 4.0相比3.5支持更多的交互格式,本篇就说说在Server与Client间通过最原始的流的格式进行通讯。开篇之前,介绍REST WCF 的一个特性:DescriptionAttribute。对这个特性相信都很熟悉,它的作用如同在WebService中通过它来标注出某个接口的描述信息,在REST WCF中同样如此。将它标注在REST WCF 接口中后,在help页面中将会显示接口的描述信息。
如以往,本篇将通过Demo的形式介绍如何在REST WCF中使用Stream。Demo的功能有以下几点: 1、通过Stream的形式获取服务端的图片资源,并保存到本地 2、通过Stream上传本地资源【一个为上传图片,另外一个为上传文件】到服务端。 开发环境:VS2010。 首先给出服务端代码:public class RawService{ [WebGet(UriTemplate = "/")] //[Description("服务测试")] public string HelloRest() { return "Hello,Rest !"; } [WebGet(UriTemplate = "{image}")] [Description("获取图片")] public Stream GetImage(string image) { string imageType = Path.GetExtension(image).TrimStart('.'); WebOperationContext.Current.OutgoingResponse.ContentType = "image/" + imageType; string path = System.Web.HttpContext.Current.Server.MapPath("~/Image"); return File.OpenRead(Path.Combine(path, image)); } [WebInvoke(UriTemplate = "upload/{fileName}")] [Description("保存图片")] public void SaveImage(string fileName,Stream fileStream) { Image img = Image.FromStream(fileStream); string path = System.Web.HttpContext.Current.Server.MapPath("~/Image"); img.Save(Path.Combine(path, fileName)); } [OperationContract] [WebInvoke(UriTemplate = "UploadFile/{fileName}", Method = "POST", ResponseFormat = WebMessageFormat.Json)] public bool UploadFile(string fileName, Stream stream) { string path = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/UploadDocument"), fileName); try { using (StreamReader sr = new StreamReader(stream)) { string str= sr.ReadToEnd(); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { fs.Write(buffer, 0, buffer.Length); } } return true; } catch { return false; } }}
我们通过浏览器访问一下资源,如下图:
注意:在WebGet方法中,通过WebOperationContext.Current.OutgoingResponse.ContentType = "image/" + imageType; 指定了文件的现实方式。
获取图片资源,并保存在本地时,由于服务是以Stream的形式返回的,所以本地获取到以后,将流写入到图片文件就行了。代码如下
:const string uri = "http://localhost:23957/RawService/test.png";HttpClient client=new HttpClient();HttpResponseMessage responseMessage=client.Get(uri);HttpContent httpContent = responseMessage.Content;string path = Server.MapPath("Image");using (FileStream fs=new FileStream(Path.Combine(path,"downLoad.jpg"),FileMode.CreateNew)){ httpContent.WriteTo(fs);}
上传图片到服务器:
const string fileName = "test.png";const string url = "http://localhost:23957/RawService/upload/" + fileName;const string file = @"C:\Documents and Settings\Administrator\桌面\2011-11-18_165714.png";HttpClient client = new HttpClient();HttpContent content = HttpContent.Create(File.OpenRead(file));HttpResponseMessage resp = client.Post(url, content);resp.EnsureStatusIsSuccessful();
需要注意的一点是:上传文件的时,有可能需要我们通过MaxReceivedMessageSize设置上传的上限。
MaxReceivedMessageSize的作用是:获取或设置配置了此绑定的通道上可以接收的消息的最大大小。设置值的类型:Int64。默认值为 65,536 字节。如果上传的图片过大,则需要更改配置,以使客户端能上传较大的文件到服务端。配置如下:
上传文件到服务端。我这里使用的本地文件为文本文档。其他文件类型也类似。代码如下:
const string fileName = "RestUploaded.txt";const string url = "http://localhost:23957/RawService/UploadFile/" + fileName;const string file = @"C:\Documents and Settings\Administrator\桌面\Rest.txt";HttpClient client = new HttpClient();HttpContent content = HttpContent.Create(File.OpenRead(file));HttpResponseMessage responseMessage = client.Post(url, content);responseMessage.EnsureStatusIsSuccessful();string result = responseMessage.Content.ReadAsString();Response.Write(result);
附注:本篇通过HttpClient来访问资源,使用的程序集为:Microsoft.Http.Extensions.dll与Microsoft.Http.dll。
参考:MSDN
代码下载: