Use the WCF web HTTP programming model to create a service that returns arbitrary data

Source: Internet
Author: User

Sometimes, developers must have full control over how data is returned from service operations.
This occurs when service operations must return data in a format not supported by WCF. This topic describes how to use the WCF web HTTP programming model to create such a service.
This service has an operation to return a stream.

Implementing service agreements
  1. Define a service agreement.
    This Protocol is named iimageserver and has a method named getimage. This method returns
    Stream.

    Copy
    [ServiceContract]    public interface IImageServer    {        [WebGet]        Stream GetImage(int width, int height);    }

    Since this method returns stream, WCF assumes that the bytes returned by the service operation are fully controlled by this operation, and does not need to apply any format settings to the returned data.

  2. Implement Service Agreements.
    This Protocol has only one operation: getimage.
    This method generates a bitmap and saves it to memorystream in. jpg format.
    Then, the operation returns the stream to the caller.

    Copy
     public class Service : IImageServer    {        public Stream GetImage(int width, int height)        {            Bitmap bitmap = new Bitmap(width, height);            for (int i = 0; i < bitmap.Width; i++)            {                for (int j = 0; j < bitmap.Height; j++)                {                    bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow);                }            }            MemoryStream ms = new MemoryStream();            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);            ms.Position = 0;            WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";            return ms;        }    }

    Pay attention to the second last line of the Code: weboperationcontext. Current. outgoingresponse. contenttype = "image/JPEG ";

    This sets the content type header to "image/JPEG ". Although this example shows how to return a. JPG file, you can modify it to return any type of data in any format. This operation must retrieve or generate data and then write it to the stream.

Bearer service
  1. Create a console application to host the service.

    Copy
    class Program{    static void Main(string[] args)    {    } }
  2. Create a variable in the main method to save the base address of the service.

    Copy
    string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
  3. Create a servicehost instance for the service and specify the service class and base address.

    Copy
    ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
  4. Use webhttpbinding and
    Add an endpoint for webhttpbehavior.

    Copy
    host.AddServiceEndpoint(typeof(IImageServer), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
  5. Open the service host.

    Copy
    host.Open()
  6. Wait for the user to press enter to terminate the service.

    Copy
    Console.WriteLine("Service is running");Console.Write("Press ENTER to close the host");Console.ReadLine();host.Close();
Use Internet Explorer to call the original service
  1. Run the service and you should see the following output from it.
    Service is running press enter to close the host

  2. Open Internet Explorer and type http: // localhost: 8000/service/getimage? Width = 50 & Height = 40, you should see a yellow rectangle with a blue diagonal line passing through its center.

Example

The complete code for this topic is listed below.

Copy
using System;using System.Collections.Generic;using System.Text;using System.ServiceModel;using System.ServiceModel.Web;using System.ServiceModel.Description;using System.IO;using System.Drawing;namespace RawImageService{    // Define the service contract    [ServiceContract]    public interface IImageServer    {        [WebGet]        Stream GetImage(int width, int height);    }    // implement the service contract    public class Service : IImageServer    {        public Stream GetImage(int width, int height)        {            // Although this method returns a jpeg, it can be            // modified to return any data you want within the stream            Bitmap bitmap = new Bitmap(width, height);            for (int i = 0; i < bitmap.Width; i++)            {                for (int j = 0; j < bitmap.Height; j++)                {                    bitmap.SetPixel(i, j, (Math.Abs(i - j) < 2) ? Color.Blue : Color.Yellow);                }            }            MemoryStream ms = new MemoryStream();            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);            ms.Position = 0;            WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";            return ms;        }    }    class Program    {        static void Main(string[] args)        {            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));            host.AddServiceEndpoint(typeof(IImageServer), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());            host.Open();            Console.WriteLine("Service is running");            Console.Write("Press ENTER to close the host");            Console.ReadLine();            host.Close();        }    }}
Compile code

  • When compiling the sample code, reference system. servicemodel. dll and system. servicemodel. Web. dll.

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.