How can I return a HTTP 401 from a WCF service?
A:
Depending on when you need to do the authorization check, you could do it in an HttpModule
using something like the following:
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.End();
WayneC
2009-12-28 07:16:32
Not exactly true...you could do this with ANY of the xHttpBindings.
WayneC
2009-12-28 16:24:55
+1
A:
If you are programming a REST-service it can be done this way:
private IWebOperationContext context = new WebOperationContextWrapper(WebOperationContext.Current); // Get the context
context.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; // Set the 401
Jochen
2009-12-28 08:16:06
A:
If you're using the WebServiceHost2 factory from the WCF REST Starter Kit, you can also throw specific WebProtocolException
and specify a HTTP return code:
There's also a HttpStatusCode.Unauthorized
which corresponds to the 401 status code.
See Rob Bagby's excellent blog post Effective Error Handling with WCF REST for more detail on the various ways of specifying HTTP return codes. (screenshots are from Rob's blog post - he deserves all the credit for this.)
marc_s
2009-12-28 08:41:36