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.rzrgm.cn/webabcd/archive/2008/12/04/1347209.html
浙公網安備 33010602011771號