从WCF服务返回401

Nev*_*hai 5 wcf http http-status-code-401

如何从WCF服务返回HTTP 401?

Tim*_*ith 6

throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized);
Run Code Online (Sandbox Code Playgroud)

笔记:

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


Joc*_*hen 5

如果您正在编写REST服务,可以通过以下方式完成:

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

context.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; // Set the 401
Run Code Online (Sandbox Code Playgroud)


Way*_*neC 0

根据您需要进行授权检查的时间,您可以使用HttpModule如下所示的方法来执行此操作:

HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.End();
Run Code Online (Sandbox Code Playgroud)