Fault Contract’1 was unhandled by user code: Solved

For a training purpose I was trying a basic demo on fault contract in WCF and to be surprised I Got below error while throwing FaultException.

clip_image002

It’s not that 1st time I was working on Fault Contract but this error was irritating. After some investigation I found there was some issue in visual studio 2013 setting. So to solve this in Visual Studio go to Tools->Options.

In General tab from Debugging section uncheck following options,

  • Enable the exception assistant
  • Enable Just My Code
  • image

    Changes in Visual Studio setting should solve the problem. Keep in mind that above error can occur due to other reasons also. Visual setting debugging option may be one way to solve above said error. I hope you find it useful. Thanks for reading.

    Publish WCF Service in Local IIS on Visual Studio 2013

    Long back I wrote a blog post Step by Step hosting WCF Service in IIS 7.5 . In this post I used Visual Studio 2012 as I remember. Today I was trying to host WCF in local IIS in Visual Studio 2013 and found it is surprisingly easy to host WCF Service in IIS 2013 in Visual Studio 2013.

    Let us assume you have created a WCF Service. Now to publish it in local IIS right click on project and from context menu select Properties.

    In Properties select Web tab. In Web tab from Servers drop down select local IIS.

    clip_image002

    Next click on Package/Publish Web tab and from Items to deploy drop down select Only Files Needed to run this application.

    clip_image004

    Now when you press F5 and run application WCF Service will be hosted in local IIS.

    clip_image006

    As you see now hosting in IIS is super easy. I hope you find this post useful. Thanks for reading.

    Solved Access-Control-Allow-Origin Error in WCF REST Service

     

    Recently I was working on a JSON based WCF REST Service. It was a simple service performing CRUD operation. When I tried to consume service from a web based client, got following errors in browser console.

    clip_image002

    Error message was, No Access-Control-Allow-Origin header is present on the required resource. Since service was running on different server and it was not configured to accept request from any origin. This error can be resolved by enabling CORS: Cross Origin Resource Sharing for the service.

    image

    You can enable CORS on service hosted on IIS or IIS Express by adding following configuration in config file.

    clip_image002[6]

    We have added a custom header that allow Access-Control-Allow-Origin value to *. By setting it * , we are allowing request from any origin to access the service. So to solve error I went ahead and added following configuration in web.config of service under system.webServer section,

    
    <system.webServer>
        
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
          </customHeaders>
        </httpProtocol>    
        
        <modules runAllManagedModulesForAllRequests="true"/>  
        <directoryBrowse enabled="true"/>
      </system.webServer>
    
    
    

     

    After adding above configuration you should able to access service in client side codes like JavaScript. I hope this post is useful.

    Dealing Multiple EndPoints of a WCF Service

    If you know EndPoints well, you know WCF well. Configuring EndPoints are vital for any WCF design. You can configure EndPoints either via code or in web.config file. I have seen many times, developers are confused with EndPoints. I have come across following common question about EndPoints

    • Can we have multiple EndPoints?
    • Can be expose same contracts on more than one EndPoint?
    • How base address works with EndPoints?
    • Can we have more than one base address?
    • How to configure EndPoint in code?
    • Do we need to configure EndPoint in self hosting?
    • Can we have more than one Service Contract?

    And many more questions of such like above.

    To answer above questions, let us start with understanding what is EndPoint?

    Endpoint identifies a WCF Service. EndPoint is combination of Address, Contract and Binding. Mathematically EndPoint can be defined as below,

    image

    Where A, B and C are as follows,

    image

    Now it is simple mathematical addition rule that if we change any of A, B or C value then we will get new E. So for any reason if you change either of Address, Contract or Binding then a new EndPoint will get created. You may have multiple EndPoints of same service

    • If same Service hosted on Multiple Address with same Binding and same Contract
    • If same Service with different Contract on same Address and for same Binding
    • If same Service with different Bindings on same Address and for same Contract.

    We can say,

    image

    As a Service designer you may consider to create multiple EndPoints in following scenarios.

    • Service wants to expose more than one type of binding.
    • Service wants to expose more than one contract on the same binding.
    • Service wants to expose same binding and contract on different addresses.

    Multiple Binding Scenario

    Now let us see how we can expose a Service on two different bindings using multiple EndPoints. For two different bindings, we will create two different EndPoints.

    Let us say we have a service as below,

    
    public interface IService1
        {
            [OperationContract]
            string  message(string name);        
    
        }
    
    

    And Service is implemented as below,

    
    public class Service1 : IService1
        {
            public string message(string name)
            {
                return "Hello " + name;
            }
        }
    
    

    We can configure multiple EndPoints as,

    
    <service name="MessagePatternDemo.Service1">
            <endpoint name="ep1"
                      address="/ep1"
                      binding="basicHttpBinding"
                contract="MessagePatternDemo.IService1"/>
            <endpoint  name="ep2"
                       address="/ep2"
                       binding="wsHttpBinding"
            contract="MessagePatternDemo.IService1"       />
            <endpoint name="mex"
                      contract="IMetadataExchange"
                      address="mex"
                      binding="mexHttpBinding" />
          </service>      
    
    

    In above configuration we are creating two EndPoints for the same service. Same Service is exposed on different bindings. Client can access same service either on basicHttpBinding or wsHttpBinding. Both EndPoints are identified with different names like ep1 and ep2. In multiple EndPoints each EndPoint will be exposed on different address with different names

    At client side same service can be consumed by passing EndPoint name.

    
    Service1Client proxy1 = new Service1Client("ep1");
                var message = proxy1.message("dj");
                Console.WriteLine(message);
                Console.ReadKey(true);
    
    

    We are passing ep1 as name of the EndPoint, so client will consume service using basicHttpBinding. If you do not pass EndPoint name at time of proxy creation then run time error will get occur while calling service.

    In above scenario, we exposed same service on multiple bindings using two different EndPoints.

    Multiple Address Scenario

    There could be scenario when you may want to expose same service on multiple base address. You can have more than one base address in service. Base address is created under host as below,

    image

    You can add more than one base address using add in baseAddresses section.Advantage of having base address is that, if we are moving service from one server to another then only base address need to be changed and all EndPoint will work on updated server. WCF allow us to give multiple base addresses for each type of protocol. And at the run time corresponding endpoint will take the base address.

    image

    So you can expose IService1 on multiple EndPoint with more than one binding as below. We are exposing IService1 with basicHttpBinding and netTcpBinding both. At the run time WCF will attach corresponding base address to respective binding.

    
    <services>
          <service name="MessagePatternDemo.Service1">
            <endpoint name="ep1"
                      address="/ep1"
                      binding="basicHttpBinding"
                contract="MessagePatternDemo.IService1"/>
            <endpoint  name="ep2"
                       address="/ep2"
                       binding="netTcpBinding"
            contract="MessagePatternDemo.IService1"/>
            <endpoint
                      contract="IMetadataExchange"
                      address="mex"
                      binding="mexHttpBinding" />
                    <endpoint address="mex1"
                      binding="mexTcpBinding"
                      contract="IMetadataExchange"/>        
    
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:8081"/>
              <add baseAddress="net.tcp://localhost:8082"/>
            </baseAddresses>
          </host>
          </service>      
    
        </services>
    
    

    You may want to host same service on different server, in that scenario also service will have same contract and binding whereas different address.

    Multiple Contract Scenario

    There could be scenario when you will have to expose multiple Service Contracts. Service Contracts will be exposed on separate EndPoints.

     

    image

    Let us say we have two services IService1 and IService2 as below,

    
    [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            string  messagefromservice1(string name);        
    
        }
    
        [ServiceContract]
        public interface IService2
        {
            [OperationContract]
            string messagefromservice2(string name);
    
        }
    
    

    And Service is implemented as below,

    
      public class Service1 : IService1, IService2
        {
            public string messagefromservice2(string name)
            {
                return "Hello " + name + "  from service1";
            }
    
            public string messagefromservice1(string name)
            {
                return "Hello " + name + "  from service2";
            }
        }
    
    

    In config file we have created multiple EndPoints exposing IService1 and IService2 as below,

    
    <services>
          <service name="MessagePatternDemo.Service1">
    
            <endpoint name="ep1"
                      address="/ep1"
                      binding="basicHttpBinding"
                contract="MessagePatternDemo.IService1"/>
    
            <endpoint  name="ep2"
                       address="/ep2"
                       binding="basicHttpBinding"
            contract="MessagePatternDemo.IService2"/>
    
            <endpoint
                      contract="IMetadataExchange"
                      address="mex"
                      binding="mexHttpBinding" />
    
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:8081"/>
            </baseAddresses>
          </host>
          </service>      
    
        </services>
    
    

    At client side while consuming service you will get information that there are two service contracts as part of the service. As you see in Add Service Reference dialog that there are two services listed and they are IService1 and IService2

    clip_image002

    To use these service you will have to create separate proxies. Both services can be consumed at client as below,

    
    Service1Client proxy1 = new Service1Client();
                var message = proxy1.messagefromservice1("dj");
                Console.WriteLine(message);
    
                Service2Client proxy2 = new Service2Client();
                var message1 = proxy2.messagefromservice2("dj");
                Console.WriteLine(message1);   
    
                Console.ReadKey(true);
    
    

    On running you will get output as below,

    image

    Having multiple EndPoints for services are sometime essential for a good service design. You may want to expose same service on different EndPoint for Internet user whereas for Intranet user on separate EndPoint. I hope this post is useful for you.

    All about Instance Management in WCF

    When I started learning WCF, First thing I learnt was “Service is just like another class”. Okay so if WCF is a class which instance of class will handle request from client? Confusing? May be! In this post let us explore WCF Instance Management.

    In WCF, Instance Management is a technique to decide which service instance will serve a client request. It also decides when a client request will be served by a service instance. Instance Management is very important factor while designing service. Its affects

    • Scalability of Service
    • Performance of Service
    • Durability of Service
    • Transactions
    • Service Queues

    Instance Management can be seen as set of techniques to decide which service instance will serve a client request and when.

    There are three different kinds of Instance Management techniques.

    1. Per-Call Instance Management technique
    2. Per-Session Instance Management technique
    3. Singleton Instance Management technique

    image

    Before we go ahead into details of Instance management, we need to understand about BEHAVIORS in WCF. Using Behaviors any service side implementation details can be abstracted from the client. Since Instance management is service side behavior, so its implementation details will be abstracted from client using Service side Behaviour. Some points about BEHAVIORS are as follows,

    • Behavior is a local attribute of service that does not affect its communication patterns.
    • Client does not aware of the Behavior.
    • Service does not manifest Behavior in binding or metadata.
    • Practically Behaviors are WCF classes.
    • Behaviors get executed at the runtime.

    There are three kinds of behaviors.

    1. Service Behaviors
    2. EndPoint Behaviors
    3. Operation Behaviors

    image

    Service Behaviors directly get apply to service implementation class. It affects all the EndPoints and it is used to configure Service Instance Mode. Operation Behaviors is used to configure operation behavior and it affects only implementation of a particular operation. It could apply only to method that implements contract operation .It is not applied to the contract definition itself.

    Now let us go back to Instance Management. We use Service Behavior to configure Instance Mode on a WCF Service. InstanceConextMode is an enum in System.ServiceModel which is used to configure Instance mode of a service.

    Enum InstanceContextMode is defined as below in System.ServiceModel.

    image

    As we saw earlier that there are three Instance Mode techniques. These three techniques work as follows,

    image

    Per-Call Instance mode creates new instance for each request from client. When client request is served instance is disposed. To demonstrate Per-Call instance technique define a service as below,

    
        [ServiceContract]
        public interface IService1
        {
    
            [OperationContract]
            int counter();     
    
        }  
    
    

    To expose service as Per-Call Instance mode, Service behavior need to be configured as below,

    image

    You just need to set InstanceContextMode as InstanceContectMode.PerCall to enable service as Per-Call Service. To demonstrate Per-Call we have implemented service as below,

     

    
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
        public class Service1 : IService1,IDisposable
        {
            static int _counter = 0;
            public Service1()
            {
                _counter = _counter + 1;
            }
           public int counter()
            {
                return _counter;
    
            }
    
            public void Dispose()
           {
               _counter = _counter - 1;
    
           }
    
        }
    
    

    In above service implementation, we have taken a static counter. To demonstrate Per-Call instance mode,

    • Incrementing value of counter in service constructor. As definition of Per-Call Instance mode on each client request service instance will get created. So for each request counter value will be increased by one in the constructor.
    • When service is served, service instance will be disposed. In disposed method we are decrementing counter by one.
    • Service is returning counter value.

    As you notice we are implanting IDispose to write our own code in Dispose method. To configure service in Per-Call Instance mode, service behavior is configured as InstanceContextMode.PerCall .

    To test Per-Call Instance mode configured service, I have created console application client.

     

    
    static void Main(string[] args)
            {
                Service1Client proxy = new Service1Client();
                var result = proxy.counter();
                Console.WriteLine(result);
                Console.ReadKey(true);
                Service1Client proxy1 = new Service1Client();
                var result1 = proxy1.counter();
                Console.WriteLine(result1);
                Console.ReadKey(true);
            }
    
    

    Run application and you will get output as

    clip_image002

    As you see we are getting 1 as output on each client request because for each client request service is creating a new instance and disposing instance once call is served. We are increasing value of counter in constructor and then decreasing it in dispose method, so across service call value of counter at service remains same.

    Ideally value of counter should increase in each request from client and you should get output something like below,

    clip_image004

    We are not getting above output because service is configured to work in Per-Call Instance Mode. To get default service as behavior as above remove Instance Mode configured as Per-Call in service configuration.

    Per-Session Instance mode creates separate Service instance for separate proxy at the client. So if a Service is configured as Per-Session or session-full service then for each proxy at client new service instance gets created. In Per-Session Instance mode is client proxy has a new service instance. In Per-Session Instance mode, WCF maintains a logical session between client and service. Service instance remains in memory throughout the session.

    In Per-Session Instance mode, when client creates new proxy either of same EndPoint or different EndPoint, Service creates new instance to serve new proxy.

    To configure service to work in Per-Session mode, there are three facets we need to take care of.

    1. Configure behavior of Service to work in Per-Session Instance mode
    2. Create EndPoint using Bindings which support sessions. For example basicHttpBinding may not support Session-full service.
    3. In contract of service we need to tell client that this service will work in session-full mode.

    image

    Let us rewrite service used in Per-Call example in Per-Session Instance Mode.

    image

    Behavior facet of session-full service is configured by configuring service Instance mode as InstanceContextMode.PerSession, WCF keeps Service instance alive for throughout the session. The session terminates when client closes the proxy. On closing proxy notifies the service that session has been closed and service calls dispose on service instance.

    Contract facet of session-full service is configured by configuring other attribute of service behavior SessionMode. SessionMode can be set to either of the following three values,

    1. Allowed
    2. NotAllowed
    3. Required

    image

    By default SessionMode is set to Allowed and it is exposed to client in Service metadata.

    When SessionMode is set to SessionMode.Allowed then transport sessions are allowed but not enforced. The behavior of service will depend on other two facets i.e. behavior configuration and binding of the service.

    Some of the points to keep in mind about allowed SessionMode are as follows,

    • If Service is configured as PerCall, it will behave as Per Call Instance Mode. Whereas, if service is configured as PerSession, it will behave as PerSession but if binding is not supporting session, it will behave as PerCall instance mode.
    • If service is configured as PerSession and binding is basicHttpBinding, which is a connection less binding then service cannot use Transport level session and it will behave as Per Call configured service.
    • If binding is WSHttpBinding and service is configured as session full service. It will act as Per-Call instance management service, if security and reliability of message is not enabled.

    When SessionMode is set to SessionMode.Required then transport session are enforced. If service is configured as SessionMode.Required with a service EndPoint in which binding does not maintain a Transport level session a run time error will encountered at executing service.

    If service is configured as PerSession and contract is configured as SessionMode.Required then service will act as session-full service. However if binding is not supporting session, it will throw run time error while executing the service.Take an example service is configured as PerSession with Contract as SessionMode.Required and binding is basicHttpBinding, which is a connectionless binding then service, cannot use Transport level session and it will throw error while service is loading.

    When SessionMode is set to SessionMode.NowAllowed then transport session are not allowed. Regardless of service configuration, if service SessionMode is set to value NotAllowed then service will behave as Per-Call service. We need to cautious before making SessionMode as NotAllowed. For example TCP and IPC protocols maintain a session at Transport level, so if End Point is configured as NetTcpBinding or NetNamePipeBinding and contract as SessionMode.NowAllowed , WCF throw an runtime error while loading the service.

    Let us see InstanceContextMode.PerSession is in action. I have created a service with SessionMode set to value Required.

     

    
    [ServiceContract(SessionMode=SessionMode.Required)]
        public interface IService1
        {
            [OperationContract]
            int counter();    
    
        }  
    
    

     

    Next we implement the service in exactly the same way implemented for InstanceContextMode.PerCall. However in this service is configured in InstanceContextMode.PerSession mode.

     

    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
        public class Service1 : IService1
        {
            static int _counter = 0;
            public Service1()
            {
                _counter = _counter + 1;
            }
           public int counter()
            {
                return _counter;
    
            }
    
            public void Dispose()
           {
               _counter = _counter - 1;
    
           }
    
        }
    
    

     

    In above service implementation, we have taken a static counter. To demonstrate Per-Session instance mode,

    • Incrementing value of counter in service constructor. As definition of Per-Session Instance mode for each client proxy, new service instance will get created. So for each proxy counter value will be increased by one in the constructor.
    • When proxy is closed service instance will be disposed. In disposed method we are decrementing counter by one.
    • Service is returning counter value.

    As you notice we are implanting IDispose to write our own code in Dispose method. To configure service in Per-Session Instance mode, service behavior is configured as InstanceContextMode.PerSession .

    To test Per-Session Instance mode configured service, I have created console application client.

     

    
    Service1Client proxy1 = new Service1Client();
                var result = proxy1.counter();
                Console.WriteLine("First Call from Proxy 1 : " + result);
                var result1 = proxy1.counter();
                Console.WriteLine("Second  Call from Proxy 1 : " + result1);
                Service1Client proxy2 = new Service1Client();
                var result2 = proxy2.counter();
                Console.WriteLine("First Call from Proxy2 :" + result2);
                proxy1.Close();
                proxy2.Close();
                Console.ReadKey(true);
    
    

    Run application and you will get output as,

    clip_image002

    We can infer from output that for first proxy same service instance is being used across the calls. So for both request service is returning same value of counter. Whereas for second proxy value of counter has been increased and because a new service instance got created.

    Third instance management technique in Single or Singleton Instance Management. When a Service is configured as a Singleton, all clients connect to the same shared Service Instance regardless of EndPoint. In Single Instance management, there is only one instance of service gets created and serve to all clients.

    In Single Instance mode service Instance created only once. It created when the service host is created and lives forever. It got disposed only when host shuts down. In this instance mode client does not maintain any logical session.

    Single instance mode does not restrict client to consume a contract with session enabled. Suppose client is consuming a contract, which is having session then during the service call the Singleton service instance will have the same Session Id as of the client. When client will close the proxy that will terminate only the Transport session not the Singleton service instance. Whereas, if the client is consuming a contract, which does not have session. That client will also get connected to the same shared singleton service instance.

    There are some disadvantages of using Single instance mode. Like it is having scalability problem. All requests to service will run on different worker thread, so it will cause synchronization problem. Only one client could have access to singleton service instance at a time. It will decrease throughput of the service. Responsiveness is very low. Single instance mode should only be used, when no other options are available. For instance Global Log Book, Single Communication Port etc.

    Let us go ahead and implement Single instance mode. To demonstrate Single instance mode, I have created two service contract. First service contract is configured with SessionMode.Required and second service contract is configured with SessionMode.Allowed.

     

    
    [ServiceContract(SessionMode=SessionMode.Required)]
        public interface IService1
        {
            [OperationContract]
            int CounterSessionRequired();        
    
        }
    
        [ServiceContract(SessionMode = SessionMode.NotAllowed)]
        public interface IService2
        {
    
            [OperationContract]
            int CounterSessionNotAllowed();
    
        }
    
    

    Next we have implemented service as below. Same implantation of PerCall or PerSession instance mode is being used here to demonstrate Single instance mode

     

    
        [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
        public class Service1 : IService1,IService2
        {
            static int _counter = 0;
            public int CounterSessionRequired()
            {
                _counter++;
                return _counter;
    
            }
    
            public int CounterSessionNotAllowed()
            {
                _counter++;
                return _counter;
    
            }
    
        }
    
    

    In above service implementation, we have taken a static counter. To demonstrate Single instance mode. We are increasing value of counter in operation contracts of different service contracts. We are going to expose these two service contract on different addresses. This can be configured as below,

     

    
    <services>
          <service name="MessagePatternDemo.Service1">
            <!-- Service Endpoints -->
            <endpoint address="RequiredService"
                      binding="wsHttpBinding"
                      contract="MessagePatternDemo.IService1">
            </endpoint>
    
            <endpoint address="AllowedService"
                      binding="wsHttpBinding"
                      contract="MessagePatternDemo.IService2">
    
            </endpoint>
    
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
        </services>
    
    

    Now at the client side both services are consumed as below,

     

    
    Service1Client proxy1 = new Service1Client();
                var result = proxy1.CounterSessionRequired();
                Console.WriteLine("First Call from Proxy 1 : " + result);
                Service2Client proxy2 = new Service2Client();
                var result2 = proxy2.CounterSessionNotAllowed();
                Console.WriteLine("First Call from Proxy2 :" + result2);
                proxy1.Close();
                proxy2.Close();
                Console.ReadKey(true);
    
    

    We are calling both services with different proxy but at the service side single service instance is getting created. As an output each time you will get increased value of counter from the service. So we can conclude that single instance of service is being used by all proxies at clients.

    In this post, we learn about Instance Modes on WCF Services. There are three types and we need to choose them wisely on basis of requirements. While choosing instance mode make sure that you have configured service with proper binding. For example don’t do mistake of creating Session-full service with basicHttpBinding. I hope this post is useful to you. Thanks for reading.

    Return type of One-way or Simplex WCF Service

    WCF is one of the most asked topics in interviews. Recently one of my reader sent me a mail. He asked, “What is error in following code?” His code snippet was as below,

    
    [ServiceContract]
        public interface IService1
        {
    
            [OperationContract(IsOneWay=true)]
            string  SendHello(string name);
            
        }
    
    
    

    In one sentence, problem with above code is in return type of Operation Contract. IsOneWay property of Operation Contract is set to True, which is making service message format as Simplex or One Way. A One way WCF Service cannot return anything. Its return type must be set to Void.

    image

    In given code snippet, Service is created as One Way Service and return type of operation contract is set to string and that is the reason Service is throwing run time Exception.

    image

    Given code snippet can be fixed by changing return type of operation contract from string to void.

    
    [ServiceContract]
        public interface IService1
        {
    
            [OperationContract(IsOneWay=true)]
            void  SendHello(string name);
            
        }
    
    
    

    Conclusion is one-way or Simplex WCF Service cannot return any data to client or its return type must be set to Void. If one-way service return type is set to any other return type then run time exception will be thrown.

    I hope you find this post useful. Thanks for reading.

    Create Image Server using WCF WEB HTTP Service

    Last post I wrote on WCF Web HTTP Service: why and how. This post was for beginners in which I discussed how to get it started and write your fist WCF WEB HTTP Service. In this post we will go one step further and learn to work with streams or to be precisely images. Service will return image based on the input from client. We are going to create an image server. Image server will do following task

    • Read requested image from file system on server
    • Convert that to stream
    • Return stream to clients

    We are going to create WCF WEB HTTP Service which will act as image server. So to start with let us create Service Contract.

     

    
    using System.IO;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    
    namespace Demo1
    {    
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            [WebGet]
            Stream FetchImage(string imageName);      
           
        }
    }
    
    
    

    In above Service, there is one Operation Contract which returns a stream. Operation Contract can be accessed using baseurl/FetchImage?imageName={imagename with extension}. Client will pass image name in query parameter to fetch a particular image. If image is not present on image then null would be returned from service.

    Service implementation is very simple. You need to do following steps to fetch image and return it as stream.

    Step 1: First check for existence of the image. If it exists got to step 2 else go to step 4

    Step 2: Read image as FileStream

    Step 3: Set Outgoing Request Content Type as image/jpeg

    Step 4: convert string Image does not exist as stream and return

    Service is implemented as below,

    
    public class Service1 : IService1
        {       
    
            public Stream FetchImage(string imageName)
            {
                string filePath = @"c:\\" + imageName;
    
                if (File.Exists(filePath))
                {
                    FileStream fs = File.OpenRead(filePath);
                    WebOperationContext.Current.OutgoingRequest.ContentType = "image/jpeg";
                    return fs;
                }
                else
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(" Requested Image does not exist :(");
                    MemoryStream strm = new MemoryStream(byteArray);
                    return strm;
                }
            }        
        }
    
    
    

    Service implementation is very simple but one line of code in which we are explicitly saying that outgoing response content type is image/jpeg

    image

    Already we have covered this in previous post about EndPoint configuration but for quick reference open markup of .svc file and add use Factory method System.ServiceModel.Activation.WebServiceHostFactory to create WEB HTTP Service.

    image

    This is what all you need to do to create an Image Server as WCF WEB HTTP Service. You can test server from IE browser.

    image

    And if requested image is not present then error message will be rendered as below,

    image

    Now you can go ahead and consume and work with this image server in any kind of client able to perform HTTP GET operation. In further post we will get into details of consuming this service from various kind of clients. I hope this post will help you.