我有一个WCF Rest服务,该服务在调用实际的服务方法之前通过使用IParameterInspector进行输入参数验证。现在,这些休息服务已被iPhone占用。如果参数无效,那么我抛出了FaultException,我想在iPhone(或可能是Android)端处理该异常。
好吧,我在stackoverflow中引用了很多链接,我在代码中使用了以下链接作为参考。

WCF Parameter Validation with Interceptor
以下是我的分步代码段。

=> FaultExceptionResponse类,在FaultException<T>中使用

[DataContract]
public class FaultExceptionResponse
{
        [DataMember]
        public bool Success { get; set; }

        [DataMember]
        public string ResponseString { get; set; }
}


=>下面的类验证参数。

public class ValidationParameterInspectorAttribute : Attribute, IParameterInspector, IOperationBehavior
    {

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
            if (operationName == "GetCommunicationDetailById")
            {
                var communicationChatViewModel = inputs.FirstOrDefault() as CommunicationChatViewModel;

                if (communicationChatViewModel != null &&
                    (communicationChatViewModel.iConsultCommunicationID <= 0))
                {
                    //ErrorLogger.LogErrorMessageToElmah(new ArgumentException("API Name: GetCommunicationDetailById   Parameter cannot be less than zero.", "iConsultCommunicationID"));
                    var fc = new FaultExceptionResponse { Success = false, ResponseString = "Invalid parameter found while fetching communication detail !" };
                    throw new FaultException<FaultExceptionResponse>(fc, new FaultReason(fc.ResponseString));
                }
            }
            return null;
        }

        public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
        }

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            dispatchOperation.ParameterInspectors.Add(this);
        }

        public void Validate(OperationDescription operationDescription)
        {
        }
    }


=>然后我像这样装饰我的API

[OperationContract]
[ValidationParameterInspector]
[FaultContract(typeof(FaultExceptionResponse))]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetCommunicationDetailById")]
 CommunicationChatDetailList GetCommunicationDetailById(CommunicationChatViewModel communicationParaViewModel);


一切正常,但当参数无效时,将在iPhone端抛出此faultException,它仅显示以下错误信息。

Error: {
    AFNetworkingOperationFailingURLResponseErrorKey = "<NSHTTPURLResponse: 0x7faa605faa90> { URL: http://192.168.151.40/MyWCF/Service1.svc/GetCommunicationDetailById } { status code: 400, headers {\n    \"Cache-Control\" = private;\n    \"Content-Length\" = 3319;\n    \"Content-Type\" = \"text/html\";\n    Date = \"Fri, 25 Sep 2015 15:45:14 GMT\";\n    Server = \"Microsoft-IIS/7.5\";\n    \"X-AspNet-Version\" = \"4.0.30319\";\n    \"X-Powered-By\" = \"ASP.NET\";\n} }";
    NSErrorFailingURLKey = "http://192.168.151.40/MyWCF/Service1.svc/GetCommunicationDetailById";
    NSLocalizedDescription = "Request failed: bad request (400)";
    NSUnderlyingError = "Error Domain=AFNetworkingErrorDomain Code=-1016 \"Request failed: unacceptable content-type: text/html\" UserInfo={AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7faa605faa90> { URL: http://192.168.151.40/LKPracooWCF/Service1.svc/GetCommunicationDetailById } { status code: 400, headers {\n    \"Cache-Control\" = private;\n    \"Content-Length\" = 3319;\n    \"Content-Type\" = \"text/html\";\n    Date = \"Fri, 25 Sep 2015 15:45:14 GMT\";\n    Server = \"Microsoft-IIS/7.5\";\n    \"X-AspNet-Version\" = \"4.0.30319\";\n    \"X-Powered-By\" = \"ASP.NET\";\n} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, NSErrorFailingURLKey=http://192.168.151.40/LKPracooWCF/Service1.svc/GetCommunicationDetailById
};


我没有找到我的自定义错误消息!!!!现在,如果我在Advanced Rest Client Application中测试了相同的测试用例,那么我将得到如下的自定义错误消息。

Status - 400 Bad Request
<p class="heading1">Request Error</p>
<p>The server encountered an error processing the request. The exception message is 'Invalid parameter found while fetching communication detail !'. See server logs for more details. The exception stack trace is: </p>
<p>......</p>


所以我想要的是如何在客户端(iPhone)端处理此faultException FaultException<FaultExceptionResponse> ??。

最佳答案

问题是您的服务应该返回Json,但是异常导致响应的内容类型为text / html。您可以删除使用FaultException并切换到WebFaultException,同时显式设置响应的内容类型。例如:

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
var exception = new WebFaultException<string>(
    "{ \"Success\" = \"false\", " +
    "\"ResponseString\" = \"Invalid parameter found while fetching communication detail !\" }",
    HttpStatusCode.BadRequest);
throw exception;

关于iphone - 使用IParameterInspector进行WCF参数验证并在客户端处理FaultException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32822489/

10-11 07:47