博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
REST WCF 使用Stream进行Server与Client交互
阅读量:4325 次
发布时间:2019-06-06

本文共 3729 字,大约阅读时间需要 12 分钟。

      介绍了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

代码下载: 

转载于:https://www.cnblogs.com/tyb1222/archive/2011/11/18/2254519.html

你可能感兴趣的文章
阶段3 3.SpringMVC·_02.参数绑定及自定义类型转换_2 请求参数绑定实体类型
查看>>
阶段3 3.SpringMVC·_02.参数绑定及自定义类型转换_4 请求参数绑定集合类型
查看>>
阶段3 3.SpringMVC·_02.参数绑定及自定义类型转换_3 配置解决中文乱码的过滤器
查看>>
阶段3 3.SpringMVC·_02.参数绑定及自定义类型转换_6 自定义类型转换器代码编写
查看>>
阶段3 3.SpringMVC·_02.参数绑定及自定义类型转换_5 自定义类型转换器演示异常
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_1 RequestParam注解
查看>>
阶段3 3.SpringMVC·_02.参数绑定及自定义类型转换_7 获取Servlet原生的API
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_2 RequestBody注解
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_3 PathVariable注解
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_4 HiddentHttpMethodFilter过滤器
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_6 CookieValue注解
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_5 RequestHeader注解
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_7 ModelAttribute注解
查看>>
阶段3 3.SpringMVC·_04.SpringMVC返回值类型及响应数据类型_1 搭建环境
查看>>
阶段3 3.SpringMVC·_03.SpringMVC常用注解_8 SessionAttributes注解
查看>>
阶段3 3.SpringMVC·_04.SpringMVC返回值类型及响应数据类型_3 响应之返回值是void类型...
查看>>
阶段3 3.SpringMVC·_04.SpringMVC返回值类型及响应数据类型_2 响应之返回值是String类型...
查看>>
阶段3 3.SpringMVC·_04.SpringMVC返回值类型及响应数据类型_4 响应之返回值是ModelAndView类型...
查看>>
阶段3 3.SpringMVC·_01.SpringMVC概述及入门案例_01.SpringMVC概述及入门案例
查看>>
阶段3 3.SpringMVC·_04.SpringMVC返回值类型及响应数据类型_6 响应json数据之过滤静态资源...
查看>>