Tuesday, April 06, 2010

WCF Service For HTTP Get Request

In my last article I talked about how you can put a hook by implementing some interface of WCF. In this article I am talking about how you can define one method which will act as a controller and control all the income request.

In WCF when you define the ServiceContract you can also define what will be the action which will trigger that particular method.So basically I am talking about OperationContract where you can define the Action and ReplyAction attributes.

So we will see a very small example how we can handle the Http get request.

I have one Service Contract where I have define one method call Process which take message as a input parameter and the operation contract of this method define Action and ReplyAction as * it a wild card character which will invoke this method for all the request.

[OperationContract(Action="*", ReplyAction="*")]
void Process(Message msg);

When you implements this service contract into you actual class message parameter of this class will give you the income request object and you can extract out different information from this message object.

public void Process(Message request)
{
HttpRequestMessageProperty rp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
if (rp.Method.Equals("Get", StringComparison.InvariantCultureIgnoreCase))
HttpContext.Current.Response.Write(Get(request));
}
so you can see In this code I am checking the request whether it's Get or POST and do my action on the basis of that.

In this case I don't need to create any class inherited by IServiceBehaviour or some other interface this method will be called for all hit whether some body is hitting by creating a proxy of your service which is POST or just directly typing into URL which is GET.