Home > C#, REST, WCF > WCF REST tip 3: WebOperationContext

WCF REST tip 3: WebOperationContext

People with experience in programming WCF services are probably aware that you can get information about the currently executing operation in a WCF service by retrieving the property “OperationContext.Current” inside a service method. This gives you access to incoming and outgoing message headers and properties.

This is sufficient for classic WCF services, but it lacks information that could be important for REST based WCF services. Luckily for us, Microsoft has foreseen this and they have created an additional Operation Context for these types of services: the WebOperationContext. The WebOperationContext provides easy access to various parts of the HTTP request and response messages: HTTP headers, HTTP method, …

In the following short example, I show how to retrieve the user agent of the caller and send it back formatted as JSON or as XML depending on the value of the Accept header in the request.

[DataContract]
public class UserAgentInfo
{
    public UserAgentInfo(string userAgent)
    {
        UserAgent = userAgent;
    }

    [DataMember]
    public string UserAgent { get; set; }
}
[WebGet(UriTemplate = "MyUserAgent")]
public Message GetMyUserAgent()
{
    string accept = WebOperationContext.Current.IncomingRequest.Accept;
    string userAgentValue = WebOperationContext.Current.IncomingRequest.UserAgent;
    UserAgentInfo userAgent = new UserAgentInfo(userAgentValue);

    switch (accept)
    {
        case "application/json":
            return WebOperationContext.Current.CreateJsonResponse<UserAgentInfo>(userAgent);
        default:
            return WebOperationContext.Current.CreateXmlResponse<UserAgentInfo>(userAgent);
    }
}
Advertisements
Categories: C#, REST, WCF
  1. No comments yet.
  1. October 7, 2011 at 13:41
  2. October 14, 2011 at 15:13

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: