throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized);
Run Code Online (Sandbox Code Playgroud)
笔记:
MSDN:当使用 WCF REST 端点(WebHttpBinding 和 WebHttpBehavior 或 WebScriptEnablingBehavior)时,响应中的 HTTP 状态代码会相应地设置。但是,WebFaultException 可以与非 REST 端点一起使用,其行为类似于常规的 FaultException。
如果您正在编写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)
根据您需要进行授权检查的时间,您可以使用HttpModule如下所示的方法来执行此操作:
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.End();
Run Code Online (Sandbox Code Playgroud)