2013-09-05 45 views
2

我有一個WCF服務,它訪問註冊表並返回值。我想在某些情況下爲HTTP 500返回HTTP 500響應。當我從註冊表返回空值時沒有任何異常。這是我的代碼。而不是返回「空」字符串我想返回HTTP 500響應。WCF服務。如何返回HTTP 500響應

private string baseKey = "SOFTWARE\\Action\\software\\Station"; 

public string GetCode() 
{ 
    string Code; 
    try 
    { 
     using (RegistryKey regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, 
      Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32)) 
     { 
      using (RegistryKey subKey = regKey.OpenSubKey(baseKey, false)) 
      { 
       Code = (string)subKey.GetValue("Code"); 
      }; 
     }; 

     return string.IsNullOrEmpty(Code) ? "null" : Code; 
    } 
    catch (Exception ex) 
    { 
     return "null"; 
    } 
} 

如何創建HTTP 500響應返回客戶端?

請幫忙。

回答

3

你試過這個嗎?

throw new WebFaultException<string>("Registry key not found", HttpStatusCode.InternalServerError); 
+0

酷派HttpStatusCode枚舉值。非常感謝。 – Newbee

3

如果一個異常冒泡到WCF,WCF將把HTTP狀態設置爲500並返回一個錯誤。

換句話說,拋出異常以向客戶端返回500響應。

3

你可以注入一個狀態代碼,就像這樣:

WebOperationContext ctx = WebOperationContext.Current; 
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError; 

注:InternalServerError是映射到HTTP 500

+0

非常感謝卡爾。我發現類似於實現的東西。 – Newbee

+0

太棒了,很高興你找到了你需要的東西。 :-) –

相關問題