2013-03-12 50 views
5

我已經看到幾個對WebServiceHost2Factory的引用,因爲class to use to effectively處理WCF Rest服務中的錯誤。顯然,在那個類中,我只需要拋出一個WebProtocolException,並且響應的主體將包含相關信息。現在WebServiceHost2Factory已經死了,如何從WCF rest服務返回錯誤文本?

現在這個班似乎已經失寵了。 .NET 4堆棧中是否有替換?

我想弄清楚如何返回POST操作的響應正文中的錯誤文本,如果出錯了。關鍵的問題是下面旁邊所有的*的

例子:

[Description("Performs a full enroll and activation of the member into the Loyalty program")] 
[OperationContract] 
[WebInvoke(Method = "POST", UriTemplate = "/fullenroll/{clientDeviceId}", 
    BodyStyle = WebMessageBodyStyle.Bare, 
    RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)] 
public MemberInfo FullEnroll(string clientDeviceId, FullEnrollmentRequest request) 
{ 
    Log.DebugFormat("FullEnroll. ClientDeviceId: {0}, Request:{1}", clientDeviceId, request); 
    MemberInfo ret = null; 
    try 
    { 
     //Do stuff 
    } 
    catch (FaultException<LoyaltyException> fex) 
    { 
     Log.ErrorFormat("[loyalty full enroll] Caught faultexception attempting to full enroll. Message: {0}, Reason: {1}, Data: {2}", fex.Message, fex.Reason, fex.Detail.ExceptionMessage); 
     HandleException("FullEnroll", fex, fex.Detail.ExceptionMessage); 
    } 
    catch (Exception e) 
    { 
     Log.ErrorFormat(
      "[loyalty full enroll] Caught exception attempting to full enroll. Exception: {0}", e); 
     HandleException("FullEnroll", e); 
    } 
    return ret; 
} 


/// <summary> 
/// Deals w/ the response when Exceptions are thrown 
/// </summary> 
private static Exception HandleException(string function, Exception e, string statusMessage = null) 
{ 
    // Set the return context, handle the error 
    if (WebOperationContext.Current != null) 
    { 
     var response = WebOperationContext.Current.OutgoingResponse; 

     // Set the error code based on the Exception 
     var errorNum = 500; 
     if (e is HttpException) 
      errorNum = ((HttpException)e).ErrorCode; 

     response.StatusCode = (HttpStatusCode) Enum.Parse(typeof (HttpStatusCode), errorNum.ToString()); 
     response.StatusDescription = statusMessage; 
     // **************************************************** 
     // How can I return this as the body of the Web Method? 
     // **************************************************** 
     WebOperationContext.Current.CreateTextResponse(statusMessage); 
    } 

    return (e is HttpException) ? e : new HttpException(500, string.Format("{0} caught an exception", function)); 
} 

回答

4

This answer似乎使用以下建議,

HttpContext.Current.Response.Write(statusMessage); 

編輯 - 作爲tobyb mentioned在評論,AspNetCompatibility是必需的。

以下是如何將其打開:

<system.serviceModel> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"> 
    <!-- ... --> 
</system.serviceModel> 
+0

這一工程!謝謝。唯一需要注意的是該服務需要AspNetCompatibility,這對我來說不是問題,但可能適用於其他人。再次感謝! – tobyb 2013-03-18 18:22:00

+0

太棒了,很高興它幫助! – Jesse 2013-03-18 23:31:04