WCF Web Extensions 1.0
Posted on by Cosmin Vana
Note: A newer version of this package is available. Please check the documentation here.
WCF Web Extensions 1.0
Nuget package which enhances WCF REST with functionalities like optional query parameters, http headers or multipart requests.
Roadmap:
- Version 1.0: Allow client to send optional query string parameters (available)
- Version 1.1: Allow client-server to use optional query string parameters in method parameters, instead of using WebOperationContext class, so that the parameters are at method level, not channel level
- Version 1.2: Allow client to send custom HTTP headers
- Version 1.3: Allow multipart/form-data requests in both client and server in a typed manner
WCF Rest Client with optional query string parameters
1. Install the following nuget package: VanaCosmin.WCF.WebExtensions
2. Call the service
using System.ServiceModel;
using System.ServiceModel.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VanaCosmin.WCF.WebExtensions.QueryParameters;
using VanaCosmin.WCF.WebExtensions.Test.TestService;
using VanaCosmin.WCF.WebExtensions.ClientExtensions;
namespace VanaCosmin.WCF.WebExtensions.Test
{
public class QueryParametersClient
{
const string ServiceUri = "http://localhost:7777/TestService";
public void CallService()
{
using (var factory = new WebChannelFactory<IQueryParametersTestService>(new WebHttpBinding()))
{
factory.Endpoint.Address = new EndpointAddress(ServiceUri);
factory.Endpoint.EndpointBehaviors.Add(new QueryParametersServiceBehavior());
using (var client = factory.CreateWebChannel())
{
client.AddQueryParameter("format", "xml");
client.AddQueryParameter("version", "2");
var result = client.Channel.GetReport();
}
}
}
}
}
Namespaces:
VanaCosmin.WCF.WebExtensions.QueryParameter - contains QueryParametersServiceBehavior class, required to append the optional parameters to the HTTP request
VanaCosmin.WCF.WebExtensions.ClientExtensions - contains CreateWebChannel factory method, which will create a wrapper over the normal factory.CreateChannel() method. It also contains the AddQueryParameter extension method over the IWebChannel wrapper.
Note: you are not required to use CreateWebChannel instead of CreateChannel over the factory class. If you use CreateChannel you need to use the AddQueryParameter like this:
(channel as IClientChannel).AddQueryParameter("key","value");
IWebChannel<T>
IWebChannel<T> is a wrapper over the normal service proxy created with factory.CreateChannel(). When you need to call a method over the channel, you need to call IWebChannel.Channel method, to get a typed interface of your own contract.
All parameters added on the IWebChannel instance containing your actual channel will be forwarded to every request made with that channel.
Server Side
To access the parameters server side, you can use WebOperationContext:
var queryParameters = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;