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("https://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.
Comments
Anonymous
July 19, 2008
PingBack from http://wordnew.acne-reveiw.info/?p=10869Anonymous
July 19, 2008
See http://blogs.msdn.com/pedram/archive/2008/04/21/how-to-consume-rest-services-with-wcf.aspx for how to consume REST services with WCFAnonymous
May 03, 2009
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?Anonymous
June 03, 2010
The comment has been removedAnonymous
January 02, 2012
The comment has been removedAnonymous
August 06, 2012
Good one I spend one whole day. why it was happend?Anonymous
March 18, 2014
Thanks a lot.