REST WCF 使用Stream进行Server与Client交互
上节介绍了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 字节。如果上传的图片过大,则需要更改配置,以使客户端能上传较大的文件到服务端。配置如下:
<standardEndpoints> <webHttpEndpoint> <standardEndpoint name= "" maxReceivedMessageSize= "2000000" helpEnabled= "true" /> </webHttpEndpoint> </standardEndpoints> |
上传文件到服务端。我这里使用的本地文件为文本文档。其他文件类型也类似。代码如下:
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。
参考:
http://blog.csdn.net/fangxinggood/archive/2011/03/19/6261431.aspx
http://www.cnblogs.com/webabcd/archive/2008/12/04/1347209.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构