How can WCF service send “Connection: close” in HTTP Response Header?

Developers have sometimes this strange desire to do odd things 🙂

One of this days a colleague of mine came out with this idea:

"I need to send a "Connection: Close" in my Http Response Header?" -  After some fighting from my part to try to understand why he would like to do such a thing, I finally give up and answer it:

"Sure it is."

So, just to share how this can be done.

In fact, this should be pretty easy, in your service, you can add the "Connection: Close" header using HttpResponseMessageProperty to the OperationContext.Current.OutgoingMessageProperties.

Basically something like this:

HttpResponseMessageProperty responseProperty;
responseProperty = new HttpResponseMessageProperty();
OperationContext.Current.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, responseProperty);
responseProperty.Headers.Add(HttpResponseHeader.Connection, "close");
OperationContext.Current.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, responseProperty);

You can do this is in a message inspector so you don’t need to add it to each service method, you just get the OperationContext from the message inspector method call instead.

If your app targets 4.5.2 and below, this won’t work without setting an app context switch. If this is the case, add the appcontext switch with name "Switch.System.ServiceModel.DisableExplicitConnectionCloseHeader" and value false.

And that's it, there you go.

Hope that helps

Comments (0)

Skip to main content