从WCF服务返回401

时间:2009-12-28 07:00:27

标签: http wcf http-status-code-401

如何从WCF服务返回HTTP 401?

4 个答案:

答案 0 :(得分:5)

如果您正在编写REST服务,可以这样做:

private IWebOperationContext context = new WebOperationContextWrapper(WebOperationContext.Current); // Get the context

context.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; // Set the 401

答案 1 :(得分:3)

throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized);

注意: “MSDN:当使用WCF REST端点(WebHttpBinding和WebHttpBehavior或WebScriptEnablingBehavior)时,响应上的HTTP状态代码会相应地设置。但是,WebFaultException可以与非REST端点一起使用,其行为类似于常规的FaultException。”

答案 2 :(得分:1)

如果您正在使用WCF REST Starter Kit中的WebServiceHost2工厂,您还可以抛出特定的WebProtocolException并指定HTTP返回码:

alt text
(来源:robbagby.com

alt text
(来源:robbagby.com

alt text
(来源:robbagby.com

还有一个HttpStatusCode.Unauthorized,对应于401状态代码。

有关指定HTTP返回码的各种方法的详细信息,请参阅Rob Bagby的优秀博文Effective Error Handling with WCF REST。 (截图来自Rob的博客文章 - 他应该得到所有的赞誉。)

答案 3 :(得分:0)

根据您何时需要进行授权检查,您可以使用以下内容在HttpModule中执行此操作:

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