Return 401 from WCF service
Asked Answered
M

4

7

How can I return a HTTP 401 from a WCF service?

Macfadyn answered 28/12, 2009 at 7:0 Comment(1)
Are doing the [OperationContract, WebInvoke] [Service] thing?Bewray
B
6
throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized);

Notes:

MSDN: When using a WCF REST endpoint (WebHttpBinding and WebHttpBehavior or WebScriptEnablingBehavior) the HTTP status code on the response is set accordingly. However, WebFaultException can be used with non-REST endpoints and behaves like a regular FaultException.

Bewray answered 28/12, 2009 at 7:0 Comment(0)
C
6

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
Crossbones answered 28/12, 2009 at 8:16 Comment(0)
C
1

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:

alt text
(source: robbagby.com)

alt text
(source: robbagby.com)

alt text
(source: robbagby.com)

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.)

Census answered 28/12, 2009 at 8:41 Comment(0)
I
0

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();
Insecure answered 28/12, 2009 at 7:16 Comment(1)
Not exactly true...you could do this with ANY of the xHttpBindings.Insecure

© 2022 - 2024 — McMap. All rights reserved.