Welcome to MSDN Blogs Sign in | Join | Help
WebChannelFactory inside a WCF Service

When using a WebChannelFactory inside a WCF service that already has an OperationContext, you may need to create a new context before being able to successfully callout using a channel created by the WebChannelFactory. (Notice the line in bold)

public class RelationService : IRelationService

{

  public Relation[] GetRelations()

  {

    var factory = new WebChannelFactory<ICustomerService>(

      new Uri("http://localhost/customerservice/customers.svc"));

    var proxy = factory.CreateChannel();

    using ((IDisposable)proxy)

    using (new OperationContextScope((IContextChannel)proxy))

    {

      var customers = proxy.GetCustomers();

      return customers.Select(c => new Relation(c.Name, c.Age)).ToArray();

    }

  }

}

In the above example, GetRelations() is a RESTful service operation calling into another RESTful service located at the Uri shown above.

Without using the new context, you may get an exception similar to the following:

ProtocolException: The remote server returned an unexpected response: (405) Method Not Allowed.

When investigating further, you may notice that WCF could be using an incorrect HTTP verb for communicating with the service that exposes the GetCustomers() operation.

As it happens, here is how ICustomerService service contract looks like:

[ServiceContract]

public interface ICustomerService

{

  [OperationContract]

  [WebGet(

      UriTemplate = "/customers",

      ResponseFormat = WebMessageFormat.Xml,

      BodyStyle = WebMessageBodyStyle.Bare

  )]

  List<Customer> GetCustomers();

}

As you can see it is expecting the GET verb. Without creating a new context, WCF ends up using the POST verb which will eventually cause the above exception.

Posted: Saturday, July 19, 2008 2:32 PM by pedramr
Filed under:

Comments

pedramr said:

# July 19, 2008 6:36 PM

Alex said:

Many thanks for this hint!

I was puzzled with this issue for few days.

Would also like to know why without new context WCF uses POST instead of GET?

# May 3, 2009 6:34 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker