2011-07-24 36 views
1

我有一個支持AJAX的WCF服務(帶有enableWebScript的行爲),它具有我創建的ValidationFault。如何從AJAX啓用的WCF服務中返回JSON中的故障?

這裏的服務:

[ServiceContract] 
public interface ICoreWCF 
{ 
    /// <summary> 
    /// Saves the Customer. 
    /// </summary> 
    [OperationContract] 
    [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
    [FaultContract(typeof(ValidationFault))] 
    void Customer_Save(Customer customer); 
} 

這裏的故障:

[DataContract] 
public class ValidationFault 
{ 
    [DataMember(Name = "success")] 
    public bool Success { get; set; } 

    [DataMember(Name = "msg")] 
    public string ValidationMessage { get; set; } 

    [DataMember(Name = "errors")] 
    public Dictionary<string, string> Errors { get; set; } 
} 

我想這個故障發送回客戶端的JavaScript。 問題是,我的自定義錯誤的DataMembers被忽略,並返回一般異常。

如何將錯誤集合發送給客戶端?

我已經嘗試過寫我自己IErrorHandler類似this,使得它使用異常處理應用程序塊到一個異常轉換成一個錯誤,然後將IErrorHandler序列化所產生的故障。但是看起來WebScriptingEnablingBehavior的JsonErrorHandler不能很好地處理生成的Message對象。

謝謝。

在webinvoke
+0

看看[這裏] [1]已經被回答了。 [1]:http://stackoverflow.com/questions/1272877/returning-error-details-from-ajax-enabled-wcf-service –

+0

謝謝@Bryan。我看到了這個問題,但不幸的是,我遇到了與此答案所述相同的問題:http://stackoverflow.com/questions/1272877/returning-error-details-from-ajax-enabled-wcf-service/3705135#3705135 –

回答

0

您可以添加RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json 嘗試

+0

謝謝亞平寧。不幸的是,這並沒有解決問題.. –

0

如果您已實現IErrorHandler和相關的IT利用WebHttpBehavior繼承自定義行爲使用以服務爲短視的鏈接,那麼也許你應該嘗試添加默認的請求/響應格式等。例如,

private class CustomWebScriptBehavior : WebHttpBehavior 
{ 
    protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, 
     System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) 
    { 
     // clear current error handlers 
     endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear(); 
     // add our error handler 
     endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(
       new ErrorHandler(true)); 
    } 

    private WebMessageFormat _requestFormat; 
    private WebMessageFormat _responseFormat; 

    public CustomWebScriptBehavior() 
    { 
     _requestFormat = _responseFormat = WebMessageFormat.Json; 
    } 

    public override bool AutomaticFormatSelectionEnabled 
    { 
     get { return false; } 
     set { throw new NotSupportedException(); } 
    } 

    public override WebMessageBodyStyle DefaultBodyStyle 
    { 
     get { return WebMessageBodyStyle.WrappedRequest; } 
     set { throw new NotSupportedException(); } 
    } 

    public override WebMessageFormat DefaultOutgoingRequestFormat 
    { 
     get { return _requestFormat; } 
     set { _requestFormat = value; } 
    } 

    public override WebMessageFormat DefaultOutgoingResponseFormat 
    { 
     get { return _responseFormat; } 
     set { _responseFormat = value; } 
    } 
} 

這將消除爲每種方法指定WebInvoke屬性的必要性。

+0

感謝您的答案,VinayC,但不幸的是,這並沒有解決我的問題。 –

相關問題