Objective
This article will give a very simple and basic explanation of , how to fetch an image using WCF REST service.
Step 1
Create a WCF application. To create a new application File -> New -> Web-> WCF Service Application.Remove all the default code created by WCF. Remove code from IService 1 interface and Service1 class. Remove the code from Web.Config also. Open Web.Config and remove System.Servicemodel codes.
Step 2
Right click on Service1.svc select View markup and add below code
<%@
ServiceHost
Language=”C#”
Debug=”true”
Service=”FetchingImageinBrowser.Service1″
CodeBehind=”Service1.svc.cs”
Factory=”System.ServiceModel.Activation.WebServiceHostFactory”
%>
Step 3
Create contract. Operation contract will return Stream. Stream is in the namespace System.IO. By putting WebGet attribute make operation contract
IService1.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Runtime.Serialization;
5 using System.ServiceModel;
6 using System.ServiceModel.Web;
7 using System.Text;
8 using System.IO;
9 namespace FetchingImageinBrowser
10 {
11 [ServiceContract]
12 public interface IService1
13 {
14
15 [OperationContract]
16 [WebGet(UriTemplate = “GetImage”, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
17 Stream GetImage();
18
19 }
20 }
21
22
23
Implement service. In service class write the below code. Using FileStream open and read the image. Then set outgoing response as image/jpeg using WebOperationContext class.
Service1.svc.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Runtime.Serialization;
5 using System.ServiceModel;
6 using System.ServiceModel.Web;
7 using System.Text;
8 using System.IO;
9
10 namespace FetchingImageinBrowser
11 {
12 public class Service1 : IService1
13 {
14 public Stream GetImage()
15 {
16 FileStream fs = File.OpenRead(@”D:\a.jpg”);
17 WebOperationContext.Current.OutgoingResponse.ContentType = “image/jpeg”;
18 return fs;
19 }
20
21 }
22 }
23
Step 4
Press F5 to run the application. Append GetImage/ in URL to get the output.
Leave a Reply