401 return from WCF service

How can I return HTTP 401 from WCF service?

+5
source share
4 answers

If you are programming a REST service, this can be done as follows:

private IWebOperationContext context = new WebOperationContextWrapper(WebOperationContext.Current); // Get the context context.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; // Set the 401 
+5
source
 throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized); 

Notes: "MSDN: when using a WCF REST endpoint (WebHttpBinding and WebHttpBehavior or WebScriptEnablingBehavior), the HTTP status code in the response is set accordingly. However, WebFaultException can be used with endpoints without REST and behaves like a regular FaultException."

+3
source

If you use the WebServiceHost2 factory from the WebProtocolException WCF REST set, you can also WebProtocolException defined by WebProtocolException and specify an HTTP return code:

alt text
(source: robbagby.com )

alt text
(source: robbagby.com )

alt text
(source: robbagby.com )

There is also HttpStatusCode.Unauthorized which corresponds to status code 401.

See Rob Bagby's excellent blog post, Effective Error Handling with WCF REST, for more information on the various ways to specify HTTP return codes. (screenshots from Rob's post - he deserves all praise for this.)

+1
source

Depending on when you need to perform an authorization check, you can do this in the HttpModule using something like the following:

 HttpContext context = HttpContext.Current; context.Response.StatusCode = 401; context.Response.End(); 
0
source

Source: https://habr.com/ru/post/925394/


All Articles