作为FaultException的低级WCF异常

时间:2014-03-05 09:09:50

标签: c# wcf

当我使用无效的操作请求调用我的WCF服务时,我得到了一个异常。我需要将此异常作为FaultException发送。

我尝试了以下方案: -

  • 我使用了IErrorHandler,但ProvideFault函数未响应此服务调用(在其他情况下,它正常工作)。

  • 我还使用了消息检查器来处理异常。但是在此次调用期间,AfterReceiveRequestBeforeSendReply也未点击。

    如何将所有类型的异常作为FaultException

  • 发送

请求服务

请求:   POST / 0710 HTTP / 1.1

页眉:   连接:关闭   内容长度:11   Content-Type:application / soap + xml;字符集= UTF-8;行动= “无效:S.O.A.P.:动作...”   主持人:userpc:9001

体:

发生异常(来自跟踪日志)

例外类型

System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

消息

无法识别的讯息版本。

堆栈跟踪

System.ServiceModel.Channels.ReceivedMessage.ReadStartEnvelope(XmlDictionaryReader reader)
System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState, Boolean[] understoodHeaders, Boolean understoodHeadersModified)
System.ServiceModel.Channels.BufferedMessage..ctor(IBufferedMessageData messageData, RecycledMessageState recycledMessageState)
System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.ReadMessage(ArraySegment`1 buffer, BufferManager bufferManager, String contentType)
System.ServiceModel.Channels.HttpInput.DecodeBufferedMessage(ArraySegment`1 buffer, Stream inputStream)
System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult.ContinueReading(Int32 bytesRead)
System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult.DecodeBufferedMessageAsync()
System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult.BeginParse()
System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult..ctor(HttpRequestMessage httpRequestMessage, HttpInput httpInput, AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpInput.BeginParseIncomingMessage(HttpRequestMessage httpRequestMessage, AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpInput.BeginParseIncomingMessage(AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginParseIncomingMessage(AsyncCallback asynCallback, Object state)
System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult..ctor(ReplyChannelAcceptor acceptor, Action dequeuedCallback, HttpPipeline pipeline, AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpRequestContext.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action acceptorCallback, AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1..ctor(HttpRequestContext requestContext, Action acceptorCallback, HttpChannelListener`1 listener, AsyncCallback callback, Object state)
System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
System.ServiceModel.Channels.SharedHttpTransportManager.EnqueueContext(IAsyncResult listenerContextResult)
System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult listenerContextResult)
System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.Net.LazyAsyncResult.Complete(IntPtr userToken)
System.Net.ListenerAsyncResult.IOCompleted(ListenerAsyncResult asyncResult, UInt32 errorCode, UInt32 numBytes)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

您可以使用以下代码

调用任何WCF服务来创建类似情况
public static string HttpPost(string URI)
        {
            try
            {
                var r = (HttpWebRequest) WebRequest.Create(URI);
                r.Method = "POST";
                r.ContentType = @"application/soap+xml; charset=utf-8; action=""Invalid:S.O.A.P.:Action...""";                           
                var ws = new StreamWriter(r.GetRequestStream());
                ws.Write("<EmptyXml/>");
                ws.Close();
                var resp = (HttpWebResponse) r.GetResponse();
                var sr = new StreamReader(resp.GetResponseStream());
                return sr.ReadToEnd();
            }
            catch (FaultException ex)
            {
                //I need to catch low level exception as Fault exception
            }
            catch (CommunicationException ex)
            {

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception : " + ex.Message);
            }
            return null;
        }

1 个答案:

答案 0 :(得分:0)

由于您正在使用HttpWebRequest,因此您将永远不会通过webrequest获得错误认识。

要获得您的错误,您必须从webexception响应中读取它。

=&GT;

try
        {
            var r = (HttpWebRequest)WebRequest.Create("/S");
            r.Method = "POST";
            r.ContentType = @"text/json; charset=utf-8; action=""Invalid:S.O.A.P.:Action...""";
            var js = new JavaScriptSerializer();
            string postData = js.Serialize(new {something = "Hello World"});
            r.ContentLength = postData.Length;
            var ws = new StreamWriter(r.GetRequestStream());
            ws.Write(postData);
            ws.Close();
            var resp = (HttpWebResponse)r.GetResponse();

            var respStream = resp.GetResponseStream();
            if (respStream == null) return;
            var sr = new StreamReader(respStream);
            string s = sr.ReadToEnd();
        }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                {
                    if (stream == null) return;
                    using (var reader = new StreamReader(stream))
                    {
//At this point i'm just writing it to the console. However her you have your FaultException xml encoded.
                        Console.WriteLine(reader.ReadToEnd());
                    }
                }
            }