Over a million developers have joined DZone.

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);
    }
}
Topics:

Published at DZone with permission of Pieter De Rycke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}