How to: Create a Basic WCF Web HTTP Service - WCF (2024)

  • Article

Windows Communication Foundation (WCF) allows you to create a service that exposes a Web endpoint. Web endpoints send data by XML or JSON, there is no SOAP envelope. This topic demonstrates how to expose such an endpoint.

Note

The only way to secure a Web endpoint is to expose it through HTTPS, using transport security. When using message-based security, security information is usually placed in SOAP headers and because the messages sent to non-SOAP endpoints contain no SOAP envelope, there is nowhere to place the security information and you must rely on transport security.

To create a Web endpoint

  1. Define a service contract using an interface marked with the ServiceContractAttribute, WebInvokeAttribute and the WebGetAttribute attributes.

    [ServiceContract]public interface IService{ [OperationContract] [WebGet] string EchoWithGet(string s); [OperationContract] [WebInvoke] string EchoWithPost(string s);}
    <ServiceContract()> _Public Interface IService <OperationContract()> _ <WebGet()> _ Function EchoWithGet(ByVal s As String) As String <OperationContract()> _ <WebInvoke()> _ Function EchoWithPost(ByVal s As String) As Stringend interface

    Note

    By default, WebInvokeAttribute maps POST calls to the operation. You can, however, specify the HTTP method (for example, HEAD, PUT, or DELETE) to map to the operation by specifying a "method=" parameter. WebGetAttribute does not have a "method=" parameter and only maps GET calls to the service operation.

  2. Implement the service contract.

    public class Service : IService{ public string EchoWithGet(string s) { return "You said " + s; } public string EchoWithPost(string s) { return "You said " + s; }}
    Public Class Service Implements IService Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet Return "You said " + s End Function Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost Return "You said " + s End FunctionEnd Class

To host the service

  1. Create a WebServiceHost object.

    WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
    Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
  2. Add a ServiceEndpoint with the WebHttpBehavior.

    ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
    Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")

    Note

    If you do not add an endpoint, WebServiceHost automatically creates a default endpoint. WebServiceHost also adds WebHttpBehavior and disables the HTTP Help page and the Web Services Description Language (WSDL) GET functionality so the metadata endpoint does not interfere with the default HTTP endpoint.

    Adding a non-SOAP endpoint with a URL of "" causes unexpected behavior when an attempt is made to call an operation on the endpoint. The reason for this is the listen URI of the endpoint is the same as the URI for the help page (the page that is displayed when you browse to the base address of a WCF service).

    You can do one of the following actions to prevent this from happening:

    • Always specify a non-blank URI for a non-SOAP endpoint.
    • Turn off the help page. This can be done with the following code:
    ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();sdb.HttpHelpPageEnabled = false;
    Dim sdb As ServiceDebugBehavior = host.Description.Behaviors.Find(Of ServiceDebugBehavior)()sdb.HttpHelpPageEnabled = False
  3. Open the service host and wait until the user presses ENTER.

    host.Open();Console.WriteLine("Service is running");Console.WriteLine("Press enter to quit...");Console.ReadLine();host.Close();
    host.Open()Console.WriteLine("Service is running")Console.WriteLine("Press enter to quit...")Console.ReadLine()host.Close()

    This sample demonstrates how to host a Web-Style service with a console application. You can also host such a service within IIS. To do this, specify the WebServiceHostFactory class in a .svc file as the following code demonstrates.

    <%ServiceHost language=c# Debug="true" Service="Microsoft.Samples.Service" Factory=System.ServiceModel.Activation.WebServiceHostFactory%>

To call service operations mapped to GET in a browser

  1. Open a web browser, enter the URL "http://localhost:8000/EchoWithGet?s=Hello, world!", and then press Enter. The URL contains the base address of the service (http://localhost:8000/), the relative address of the endpoint (""), the service operation to call ("EchoWithGet"), and a question mark followed by a list of named parameters separated by an ampersand (&).

To call service operations in code

  1. Create an instance of ChannelFactory<TChannel> within a using block.

    using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
    Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")
  2. Add WebHttpBehavior to the endpoint the ChannelFactory<TChannel> calls.

    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
    cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
  3. Create the channel and call the service.

    IService channel = cf.CreateChannel();string s;Console.WriteLine("Calling EchoWithGet via HTTP GET: ");s = channel.EchoWithGet("Hello, world");Console.WriteLine(" Output: {0}", s);Console.WriteLine("");Console.WriteLine("This can also be accomplished by navigating to");Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!");Console.WriteLine("in a web browser while this sample is running.");Console.WriteLine("");Console.WriteLine("Calling EchoWithPost via HTTP POST: ");s = channel.EchoWithPost("Hello, world");Console.WriteLine(" Output: {0}", s);
    Dim channel As IService = cf.CreateChannel()Dim s As StringConsole.WriteLine("Calling EchoWithGet via HTTP GET: ")s = channel.EchoWithGet("Hello, world")Console.WriteLine(" Output: {0}", s)Console.WriteLine("")Console.WriteLine("This can also be accomplished by navigating to")Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!")Console.WriteLine("in a web browser while this sample is running.")Console.WriteLine("")Console.WriteLine("Calling EchoWithPost via HTTP POST: ")s = channel.EchoWithPost("Hello, world")Console.WriteLine(" Output: {0}", s)
  4. Close the WebServiceHost.

    host.Close();
    host.Close()

Example

The following is the full code listing for this example.

// Service.csusing System;using System.Collections.Generic;using System.ServiceModel;using System.ServiceModel.Description;using System.ServiceModel.Web;using System.Text;namespace Microsoft.ServiceModel.Samples.BasicWebProgramming{ [ServiceContract] public interface IService { [OperationContract] [WebGet] string EchoWithGet(string s); [OperationContract] [WebInvoke] string EchoWithPost(string s); } public class Service : IService { public string EchoWithGet(string s) { return "You said " + s; } public string EchoWithPost(string s) { return "You said " + s; } } class Program { static void Main(string[] args) { WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/")); try { ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), ""); host.Open(); using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000")) { cf.Endpoint.Behaviors.Add(new WebHttpBehavior()); IService channel = cf.CreateChannel(); string s; Console.WriteLine("Calling EchoWithGet via HTTP GET: "); s = channel.EchoWithGet("Hello, world"); Console.WriteLine(" Output: {0}", s); Console.WriteLine(""); Console.WriteLine("This can also be accomplished by navigating to"); Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!"); Console.WriteLine("in a web browser while this sample is running."); Console.WriteLine(""); Console.WriteLine("Calling EchoWithPost via HTTP POST: "); s = channel.EchoWithPost("Hello, world"); Console.WriteLine(" Output: {0}", s); Console.WriteLine(""); } Console.WriteLine("Press <ENTER> to terminate"); Console.ReadLine(); host.Close(); } catch (CommunicationException cex) { Console.WriteLine("An exception occurred: {0}", cex.Message); host.Abort(); } } }}
'Service.csImports System.Collections.GenericImports System.ServiceModelImports System.ServiceModel.DescriptionImports System.ServiceModel.WebImports System.Text<ServiceContract()> _Public Interface IService <OperationContract()> _ <WebGet()> _ Function EchoWithGet(ByVal s As String) As String <OperationContract()> _ <WebInvoke()> _ Function EchoWithPost(ByVal s As String) As Stringend interfacePublic Class Service Implements IService Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet Return "You said " + s End Function Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost Return "You said " + s End FunctionEnd ClassModule program Sub Main() Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/")) Try Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "") host.Open() Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000") cf.Endpoint.Behaviors.Add(New WebHttpBehavior()) Dim channel As IService = cf.CreateChannel() Dim s As String Console.WriteLine("Calling EchoWithGet via HTTP GET: ") s = channel.EchoWithGet("Hello, world") Console.WriteLine(" Output: {0}", s) Console.WriteLine("") Console.WriteLine("This can also be accomplished by navigating to") Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!") Console.WriteLine("in a web browser while this sample is running.") Console.WriteLine("") Console.WriteLine("Calling EchoWithPost via HTTP POST: ") s = channel.EchoWithPost("Hello, world") Console.WriteLine(" Output: {0}", s) Console.WriteLine("") End Using Console.WriteLine("Press <ENTER> to terminate") Console.ReadLine() host.Close() Catch cex As CommunicationException Console.WriteLine("An exception occurred: {0}", cex.Message) host.Abort() End Try End SubEnd Module

Compiling the code

When compiling Service.cs reference System.ServiceModel.dll and System.ServiceModel.Web.dll.

See also

  • WebHttpBinding
  • WebGetAttribute
  • WebInvokeAttribute
  • WebServiceHost
  • WebHttpBehavior
  • WCF Web HTTP Programming Model
How to: Create a Basic WCF Web HTTP Service - WCF (2024)

FAQs

How to create a basic WCF Web HTTP service? ›

Creating a WCF Service

You can do this by opening Visual Studio, clicking on File > New > Project. Then, select the 'WCF' option and click on 'WCF Service Library'. The code above defines a WCF service with a single endpoint. The 'binding' attribute specifies how the service can be accessed.

How to create WCF in C#? ›

Also, a basic understanding of C# will be helpful.
  1. Step 1: Creating a new WCF Service Application. First, open Visual Studio and create a new project. ...
  2. Step 2: Defining the Service Contract. ...
  3. Step 3: Implementing the Service Contract. ...
  4. Step 4: Configuring the Service. ...
  5. Step 5: Hosting and Testing the Service.
Jul 21, 2023

How do I make my WCF service https? ›

Configuring WCF to use Workflow designer under both HTTP and HTTPS
  1. Open the Workflow web. config file located in ~/CMSModules/Workflows.
  2. Create a binding based on WebHttpBinding in the <system. serviceModel> - <bindings> section. ...
  3. Add both HTTP and HTTPS endpoints into the <service name="CMS. WebServices. ...
  4. Save the web.

How do you create a WCF project? ›

Create a service
  1. Open Visual Studio.
  2. On the start window, choose Create a new project.
  3. Type wcf service library in the search box on the Create a new project page. ...
  4. On the Configure your new project page, click Create. ...
  5. In Solution Explorer, double-click IService1. ...
  6. In Solution Explorer, double-click Service1.

How to create HTTP service? ›

  1. Create an HTTP service.
  2. Implement the handler class.
  3. Test the service.
  4. Add method `get_html`
  5. Test the service again (optional)
  6. Check code.
  7. Create an inbound Communication Scenario.
  8. Add the HTTP service.
Mar 9, 2023

How do I create a basic Web service? ›

Take the following steps to create the web service: Step (1) : Select File -> New -> Web Site in Visual Studio, and then select ASP.NET Web Service. Step (2) : A web service file called Service. asmx and its code behind file, Service.

What is WCF service with example? ›

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

When to use WCF in C#? ›

Use WCF to create reliable, secure web services that are accessible over a variety of transports. Use ASP.NET Web API to create HTTP-based services that are accessible from a wide variety of clients. Use ASP.NET Web API if you are creating and designing new REST-style services.

What is the difference between Web API and WCF service? ›

WCF is used for SOAP-based service development, whereas Web API is utilized for both SOAP-based and RESTful service development. WCF does not provide support for MVC functionalities, although Web API does. WCF supports HTTP, UDP, and custom transport protocols, whereas Web API only supports HTTP.

How to create a WCF rest service? ›

Creating a WCF service
  1. Open Visual Studio 2015.
  2. In the File menu in the Visual Studio IDE, click on Start -> File -> New -> Project.
  3. Next, select WCF from the list of the project templates displayed.
  4. Select “WCF Service Application” on the right side pane.
  5. Specify a name for your WCF service project and click OK to save it.
Apr 26, 2016

How do I add a WCF service? ›

In Solution Explorer, right-click the name of the project to which you want to add the service, and then click Add Service Reference. The Add Service Reference dialog box appears. Click Discover. All services (both WCF Data Services and WCF services) in the current solution are added to the Services list.

How do I enable WCF HTTP activation? ›

Activate Windows Communication Foundation (WCF)
  1. From the Start menu, select Administrative Tools > Server Manager.
  2. Select Add roles and features from the Dashboard.
  3. Select Next twice.
  4. Select Features.
  5. In the Features area, expand the: - . ...
  6. Under WCF Services select: - HTTP Activation.

How to create a simple WCF service in C#? ›

Open Visual Studio. On the start window, choose Create a new project. Type wcf service library in the search box on the Create a new project page. Select either the C# or Visual Basic template for WCF Service Library, and then click Next.

How to start a WCF service? ›

The WCF service can only respond to clients if the Windows service is running. To start the service, right-click it in the SCM and select "Start", or type net start WCFWindowsServiceSample at the command prompt. If you make changes to the service, you must first stop it and uninstall it.

What are the basics of WCF? ›

Some key concepts to understand in WCF:
  • SOAP and REST. ...
  • Message Exchange Patterns. ...
  • Endpoints. ...
  • Addresses, Bindings and Contracts. ...
  • Hosting. ...
  • Defining Service Contracts. ...
  • Defining Data Contracts. ...
  • Service and Data Contract Separation.
Dec 28, 2023

Does WCF support HTTP? ›

WCF services and clients can communicate over HTTP and HTTPS. The HTTP/HTTPS settings are configured by using Internet Information Services (IIS) or through the use of a command-line tool.

How do I add WCF service to my web application? ›

In Solution Explorer, right-click the name of the project to which you want to add the service, and then click Add Service Reference. The Add Service Reference dialog box appears. In the Address box, enter the URL for the service, and then click Go to search for the service.

References

Top Articles
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 6288

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.