ObjectiveThis article will give a very simple and basic explanation of , how to fetch an image using WCF REST service. Step 1Create a WCF application. To create a new application File -> New -> Web-> WCF Service Application. Step 2Remove 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 3Right 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 4Create contract. Operation contract will return Stream. Stream is in the namespace System.IO. By putting WebGet attribute make operation contract IService1.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO ;
namespace FetchingImageinBrowser
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "GetImage", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
Stream GetImage();
}
}
Step 5Implement 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.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO ;
namespace FetchingImageinBrowser
{
public class Service1 : IService1
{
public Stream GetImage()
{
FileStream fs = File.OpenRead(@"D:\a.jpg");
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return fs;
}
}
}
Step 6Press F5 to run the application. Append GetImage/ in URL to get the output. See the URL ConclusionIn this article, I discussed how to get an image from WCF REST service. In next articles I will show complete Get and Set image using WCF Rest service. Thanks for reading. |