Rest wcf uses Stream for Server-Client interaction

Source: Internet
Author: User

The previous section introduced that rest wcf 4.0 supports more interactive formats than 3.5. This article describes how to communicate between the Server and Client through the original stream format. Before getting started, we will introduce a feature of rest wcf: DescriptionAttribute. I believe that this feature is familiar with it. It serves to mark the description of an interface in WebService, as in REST WCF. After it is marked in the rest wcf interface, the interface description is displayed on the help page.

As in the past, this article describes how to use Stream in rest wcf through Demo. The Demo has the following functions:
1. Obtain the image resources of the server in the form of Stream and save them to the local device.
2. Use Stream to upload local resources [upload images and files] to the server.
Development Environment: VS2010.
First, the server code is provided:

Public class RawService {[WebGet (UriTemplate = "/")] // [Description ("service test")] public string HelloRest () {return "Hello, Rest! ";} [WebGet (UriTemplate =" {image} ")] [Description (" Get image ")] 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 ("Save image")] 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 ;}}}

  

We can access resources through a browser, such:

Note: In the WebGet method, the actual file method is specified through WebOperationContext. Current. OutgoingResponse. ContentType = "image/" + imageType.

When retrieving image resources and saving them locally, because the service returns the data in the form of Stream, you can write the Stream to the image file after obtaining the data locally. The Code is as follows:
:

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);}

  

Upload images to the server:

Const string fileName = "test.png"; const string url = "http: // localhost: 23957/RawService/upload/" + fileName; const string file = @ "C: \ Documents and Settings \ Administrator \ Desktop \ 2011-11-18_165714.png "; HttpClient client = new HttpClient (); HttpContent content = HttpContent. create (File. openRead (file); HttpResponseMessage resp = client. post (url, content); resp. ensureStatusIsSuccessful ();

  

Note that when uploading files, you may need to use maxcompute edmessagesize to set the upload ceiling.
Maxcompute edmessagesize is used to obtain or set the maximum size of messages that can be received on the bound channel. Set the value type: Int64. The default value is 65,536 bytes. If the uploaded image is too large, you need to change the configuration so that the client can upload large files to the server. The configuration is as follows:

<standardEndpoints><webHttpEndpoint> <standardEndpoint name="" maxReceivedMessageSize="2000000" helpEnabled="true" /></webHttpEndpoint></standardEndpoints>

  

Upload the file to the server. The local file I use here is a text document. Other file types are similar. The Code is as follows:

Const string fileName = "RestUploaded.txt"; const string url = "http: // localhost: 23957/RawService/UploadFile/" + fileName; const string file = @ "C: \ Documents and Settings \ Administrator \ Desktop \ 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 );

  

Note: In this document, HttpClient is used to access resources. Microsoft. Http. Extensions. dll and Microsoft. Http. dll are used.
Refer:

Http://blog.csdn.net/fangxinggood/archive/2011/03/19/6261431.aspx
Http://www.cnblogs.com/webabcd/archive/2008/12/04/1347209.html

MSDN
Code download: http://files.cnblogs.com/tyb1222/RestRaw.rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.