【问题标题】:How to return Faults in JSON from AJAX Enabled WCF Service?如何从启用 AJAX 的 WCF 服务返回 JSON 中的错误?
【发布时间】:2011-10-12 01:00:50
【问题描述】:

我有一个启用 AJAX 的 WCF 服务(在行为中带有 enableWebScript),它有一个我创建的 ValidationFault。

这里是服务:

[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 对象。

谢谢。

【问题讨论】:

标签: ajax wcf json exception-handling


【解决方案1】:

如果您已经实现IErrorHandler 并使用从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 属性的需要。

【讨论】:

  • 感谢 VinayC 的回答,但不幸的是,这并不能解决我的问题。
【解决方案2】:

在 webinvoke 中,您可以添加 RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json 试试看

【讨论】:

    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    相关资源
    最近更新 更多