2009-12-28 159 views

回答

0

取決於當你需要做的授權檢查,你可以使用類似做在一個HttpModule如下:

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

不完全如此......您可以使用任何xHttpBindings來做到這一點。 – WayneC 2009-12-28 16:24:55

5

如果您正在編寫一個REST的服務是可以做到這樣:

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

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

如果您使用從WCF REST入門工具包WebServiceHost2工廠,你也可以拋出具體WebProtocolException並指定一個HTTP返回代碼:

alt text http://www.robbagby.com/wp-content/uploads/effective-error-handling-with-wcf-rest/image_thumb_5.png alt text http://www.robbagby.com/wp-content/uploads/effective-error-handling-with-wcf-rest/image_thumb_10.png alt text http://www.robbagby.com/wp-content/uploads/effective-error-handling-with-wcf-rest/image_thumb_12.png

還有一個HttpStatusCode.Unauthorized對應於401個狀態碼。

有關指定HTTP返回碼的各種方式的更多詳細信息,請參閱Rob Bagby的優秀博客文章Effective Error Handling with WCF REST。 (截圖是來自Rob的博客文章 - 他是值得所有的功勞這一點。)

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

注: 「MSDN:當使用WCF REST端點(的WebHttpBinding和WebHttpBehavior或WebScriptEnablingBehavior)在響應的HTTP狀態代碼但是,WebFaultException可以與非REST端點一起使用,並且像普通的FaultException一樣運行。「