共用方式為


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