Archive

Archive for October, 2011

WCF REST tip 3: WebOperationContext

October 6, 2011 2 comments

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