Wcf4.0 -- restful WCF services (3) (raw Stream)

Source: Internet
Author: User

The first two blogs mainly introduce how rest WCF interacts with clients through JSON/XML. This article will conduct an instance analysis on native (raw) stream transmission of rest WCF.

OK, or use the project template of the WCF rest service application to create our rest WCF project.

The definition of operationcontract is also omitted because the WCF rest service does not need to expose metadata. Directly define [servicecontract]
If you modify the service name in the template,Global. asaxInRegisterroutesThe method must also be modified accordingly.
The following is the service implementation:
[Servicecontract] <br/> [aspnetcompatibilityrequirements (requirementsmode = aspnetcompatibilityrequirementsmode. allowed)] <br/> [servicebehavior (instancecontextmode = instancecontextmode. percall, namespace = "")] <br/> public class imageservice <br/>{< br/> [webget (uritemplate = "{image}")] <br/> Public stream getimage (string image) <br/>{< br/> var imagetype = path. getextension (image ). trimstart ('. '); <Br/> weboperationcontext. current. outgoingresponse. contenttype = "image/" + imagetype; <br/> var dir = system. web. httpcontext. current. server. mappath ("~ /Images "); <br/> var file = path. combine (Dir, image); <br/> return file. openread (File); <br/>}</P> <p> [webinvoke (uritemplate = "Add/{image}", method = "Post")] <br/> Public void addimage (Stream stream, string image) <br/>{< br/> var dir = system. web. httpcontext. current. server. mappath ("~ /Images "); <br/> var file = path. combine (Dir, image); <br/> var bitmap = bitmap. fromstream (Stream); <br/> bitmap. save (File); <br/>}</P> <p> [webget (uritemplate = "listall", responseformat = webmessageformat. XML)] <br/> Public String [] getallimagenames () <br/>{< br/> var dir = system. web. httpcontext. current. server. mappath ("~ /Images "); <br/> var files = directory. getfiles (DIR); <br/> var images = new list <string> (); <br/> foreach (var file in files) <br/> {<br/> var ext = path. getextension (File); <br/> If (EXT = ". jpg "| ext = ". GIF ") <br/> images. add (File); <br/>}< br/> for (INT I = 0; I <images. count; I ++) <br/> images [I] = path. getfilename (images [I]); <br/> return images. toarray (); <br/>}< br/>}

-Getimage is used to return the image stream,
-Addimage is used to accept and save the image stream,
-Getallimagenames: returns the names of all images.

In HTTP, content-type is used to control the parsing behavior of the client. When the Content-Type is "image/jpg" or "image/GIF,
The browser can directly display the image. Therefore, the following settings are available in the Code:
Weboperationcontext. Current. outgoingresponse. contenttype = "image/" + imagetype;
You can also use outgoingresponse. header to control the cache. In addition, this rest WCF is created in a web application,
We can also use the system. Web. httpcontext. Current. server. mappath method to obtain the physical path.

We know that streamed transmission can be implemented in general WCF services. In that case, the required parameter or return value of the service contract must be stream, and there cannot be other types of parameters (other parameters can be passed through messageheader ). However, in the above sample code, the addimage I defined has two parameters:
One is stream and the other is string. This string parameter is actually passed through the URL: uritemplate = "Add/{Image}", And the two parameters do not have order requirements.
If "{image}" is not written, the following exception will be thrown (because the request body has been defined as stream, and the image name can only be passed through the URL .)
Operation 'addimage' of contract 'imageservice' specifies multiple Request body parameters to be serialized without any wrapper elements. at most one body parameter can be serialized without wrapper elements. either remove the extra body parameters or set the bodystyle property on the webgetattribute/webinvokeattribute to wrapped.

Run the service and enter the service URL: http: // localhost: 3577/imageservice/gif002.gif in the browser to view the result.
In addition, we can replace the page class that used to generate a verification code or image reading step in ASP. Net by using the features of the native stream returned by rest WCF,
Is it convenient?

To reflect the convenience of rest WCF, I designed a WPF client:

Client code:
Public partial class mainwindow: Window <br/>{< br/> Public mainwindow () <br/>{< br/> initializecomponent (); <br/>}</P> <p> private void window_loaded (Object sender, routedeventargs e) <br/>{< br/> op. restoredirectory = true; <br/> op. filter = "JPEG files (*. JPG) | *. JPG | GIF files (*. GIF) | *. GIF "; </P> <p> binddata (); <br/>}</P> <p> private void binddata () <br/> {<br/> var url = "http: // localhost: 357 7/imageservice/listall "; <br/> var client = new httpclient (); <br/> var stream = client. get (URL ). content. readasstream (); <br/> var dataser = new datacontractserializer (typeof (string []); <br/> var OBJ = (string []) dataser. readobject (Stream); <br/> This. listbox1.datacontext = OBJ; <br/>}</P> <p> private Microsoft. win32.openfiledialog op = new Microsoft. win32.openfiledialog (); </P> <p> private void Ton1_click (Object sender, routedeventargs e) <br/>{< br/> var ret = op. showdialog (); <br/> If (! Ret. hasvalue |! Ret. Value |! Op. checkfileexists) return; <br/> var file = op. filename; <br/> var name = system. io. path. getfilename (File); <br/> var url = "http: // localhost: 3577/imageservice/Add/" + name; <br/> var client = new httpclient (); <br/> var content = httpcontent. create (file. openread (File); <br/> var resp = client. post (URL, content); <br/> resp. ensurestatusissuccessful (); </P> <p> binddata (); <br/>}</P> <p> private void button2_click (Object sender, routedeventargs E) <br/>{< br/> This. close (); <br/>}</P> <p> [valueconversion (typeof (string), typeof (string)] <br/> public class uriconverter: ivalueconverter <br/> {<br/> Public object convert (object value, type targettype, <br/> object parameter, system. globalization. cultureinfo culture) <br/>{< br/> If (value = NULL) return NULL; <br/> string sourcevalue = value. tostring (); <br/> return "http: // localhost: 3577/imageservice/" + sourcevalue; <br/>}</P> <p> Public object convertback (object value, type targettype, <br/> object parameter, system. globalization. cultureinfo culture) <br/>{< br/> return value; <br/>}< br/>}
Note:
1) Get all image names. The serialized XML of string [] is returned by the server and deserialized using datacontractserializer.
VaR dataser = new datacontractserializer (typeof (string []);
2) openfiledialog in WPF is in the Microsoft. Win32 namespace. (Windowsbase. dll must be referenced)
3) use Microsoft. http. httpclient to upload images, instantiate httpcontent, and upload images through client. Post.
VaR url = "http: // localhost: 3577/imageservice/Add/" + name;
VaR client = new httpclient ();
VaR content = httpcontent. Create (file. openread (File ));
VaR resp = client. Post (URL, content );
Resp. ensurestatusissuccessful ();
4) defines a converter to bind the ListBox to the source of the image control.
Source = "{bindingElementname= Listbox1,Path= Selecteditem,Converter={ Staticresource uriconv }}"

Source code download:Rest WCF raw stream sample code

[Rest WCF series]
Restful WCF Services (1) (Getting Started)
Restful WCF services (2) (implement add, delete, modify, and query)
Restful WCF services (3) (raw Stream)
Restful WCF Services (4) (Basic Security)
Restful WCF services (Instance) (concurrent Synchronization Service syncservice)

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.