find a location for property in a new city

Wednesday, 16 March 2011

WCF REST: How to add a response header

I can't believe how difficult it is to add a response header to a response to a WCF REST service. It is so round the houses it really quite difficult.

Whatever happened to Response.Headers.Add from the friendly web code I'm so used to... Oh well, after scratching around for ages I finally found how:
var prop = new HttpResponseMessageProperty();
prop.Headers.Add("ApiVersion", "v1.0");
OperationContext.Current.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, prop);

I know you're kicking yourself, right? "That's so obvious..." Ridiculous - I'm starting to thing WCF REST wasn't made with the developer in mind.

Update:

Actually, there is an easier way I found. Since this is in a REST service it is possible to use WebOperationContext which seems a lot more intuitive and concise:
WebOperationContext.Current.OutgoingResponse.Headers.Add("ApiVersion", "v1.0");

More WCF REST:

Follow britishdev on Twitter

2 comments:

  1. It's not that WCF REST wasn't made with the developer in mind; it's that WCF wasn't made with only REST in mind.

    ReplyDelete
  2. If a cookie was going to be added to a header, how could it be set to expire after 30 days from current datetime?

    ReplyDelete