How to set HttpStatusCode

Topics: Web Api
Jan 26, 2012 at 9:39 PM

Here is the method that I have in my service:

[WebInvoke(Method = "POST", UriTemplate = "perform")]
public MyDataContractObject DoOperation(MyInputObject info)

When I return MyDataContractObject. I want to set some HttpStatusCode on the response, I tried doing this using WebOperationContext.Current.OutgoingResponse.StatusCode and HttpContext.Current.Response.Status but none of this approaches work.
Is there anyway I can set the statuscode without wrapping MyDataContractObject with HttpMessageResponse<T>?



Jan 26, 2012 at 9:40 PM
Out of curiosity, what's wrong with using HttpResponseMessage<T> for this?
Jan 26, 2012 at 9:46 PM
Edited Jan 26, 2012 at 9:47 PM

I am exposing this service not only through Web Api but also using regular wcf servicehost  with nettcp binding. I need to minimize the exposure to the infrastructure the service is running under.




So it does not make any sense for a client who is using the service through nettcp binding to see HttpResponseMessage as returns from the service.

Jan 26, 2012 at 9:53 PM

Pretty sure you have to wrap it.

Jan 26, 2012 at 9:55 PM

So there is no way I can do it without HttpResponseMessage?

Jan 26, 2012 at 10:01 PM

The way the framework works is if you want to alter the httpresponsemessage... you wrap your output.

I don't know about using the servicehost with nettcp binding. I don't know if maybe you can use a custom formatter to strip out exposing the httprequestresponse or something... but I'm pretty sure the way you are supposed to do it (and the only way built into wcf api) is by wrapping your output.

WebApi isn't for SOAP so your exposed types aren't supposed to matter because the end user will never know.

Jan 27, 2012 at 4:29 AM

I understand that it does not matter for WebApi. But in my case the service has to be exposed through soap as well.

I wonder maybe there some way I can inject my code in the pipeline and modify the HttpResponseMessage that is generated by the framework.

Jan 27, 2012 at 4:34 AM

You do realize that soap and restful API are sort of mutually exclusive?

Jan 27, 2012 at 4:46 AM

Web API really takes a step away from the standard WCF model of using HTTP as just another transport. Web API treats HTTP as an application protocol. This is why you get things like a first-class HTTP message programming model. If you need to still support SOAP then you are better off using the WCF WebHTTP support in .NET 4.

It’s worth noting that we are deeply integrating Web API with ASP.NET MVC. In the integrated stack WCF plays (almost) no role, so trying to use Web API with SOAP will really become a non-starter.

Daniel Roth