2019. 9. 24. 09:36

WCF 에서 Request, Response 설정하는 방법.

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안녕하세요. 

오늘은  WCF에서 REQ, RES 관련되서 내용을 출력하는 방법에 관해 적어 볼까 합니다.

참조한 링크는 아래와 같습니다.

https://www.wiliam.com.au/wiliam-blog/easy-wcf-audit-logging

 

Easy WCF Audit Logging

I had the requirement to log every web service request and response in a recent project. WCF turned out to be an easy and useful debugging tool to achieve it.

www.wiliam.com.au

해당 부분에서 호출 안되는 부분이 있어서 변경했습니다. 참고 하시면 됩니다.

WCF에서 app.config에서 호출되는 구조는 아래와 같습니다.

Services -> endpoint -> serviceBehaviors, endpointBehaviors -> extentionBehavior..

app.config에서 설정된 항목을 통해서 각 endpoint에서 behaviorExtensions을 활용 하여 여러개의 behaiBehaviors를 지정할수 있네요. 

감사 합니다.


    public class WcfAuditMessageInspector : IDispatchMessageInspector
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("logger");

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {

    
            var abPath = request.Headers.To.AbsolutePath.ToString();
            if (abPath.Contains("xxxxx/message") )
            {
                return null;
            }


            log.Info("FROM CLIENT HEADER --> : "+ request.Headers.To);
            if (request.Headers.To.ToString().Contains("xxxxx/id"))
            {
                Console.WriteLine();
            }
            foreach (var item in request.Properties.Values)
            {
                if (item.ToString() == "System.ServiceModel.Channels.HttpRequestMessageProperty")
                {   
                    var buffer = request.CreateBufferedCopy(int.MaxValue);
                    request = buffer.CreateMessage();
                    Message msg = buffer.CreateMessage();
                    
                    StringWriter stringWriter = new StringWriter();
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                    msg.WriteMessage(xmlTextWriter);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();

                    var formattedXML = FormatXml(stringWriter.ToString());
                    if (String.IsNullOrEmpty(formattedXML) == false) log.Info("FROM CLIENT--> : " + formattedXML);
                }
            }
             

            return null;      
        }


        string FormatXml(string xml)
        {
            try
            {
                if (xml.Contains("") == true)
                {
                    var tmpResult = XDocument.Parse(xml).ToString();
                    tmpResult = tmpResult.ToString().Substring(0, 300) + " ... ";
                    return tmpResult;
                }
                else return XDocument.Parse(xml).ToString();
            }
            catch (Exception)
            {
                // Handle and throw if fatal exception here; don't just ignore them
                return xml;
            }
        }


        
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (reply.Headers.Action == null)
            {
                
                if (reply.GetType().ToString().Contains("System.ServiceModel.Channels.BodyWriterMessage") )
                {
                    var buffer = reply.CreateBufferedCopy(int.MaxValue);
                    reply = buffer.CreateMessage();
                    Message msg = buffer.CreateMessage();

                    StringWriter stringWriter = new StringWriter();
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                    msg.WriteMessage(xmlTextWriter);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();

                    var formattedXML = FormatXml(stringWriter.ToString());
                    if (String.IsNullOrEmpty(formattedXML) == false) log.Info("<--FROM SERVER : " + formattedXML);
                    
                }

            }
            else {
                switch (reply.Headers.Action.ToString())
                {
                    case "http://xxxxxx.jsonResponse":
                    case "http://xxxxxxecho.jsonResponse":
                        break;
                    default:
                        var result = reply.ToString();
                        log.Info("<--FROM SERVER HEADER : " +  result.ToString());
                        break;
                }    
            
            }
            
        }
    }


    public class WcfAuditBehaviorExtensionElement : BehaviorExtensionElement
    {
        protected override object CreateBehavior()
        {
            return new WcfAuditBehavior();
        }

        public override Type BehaviorType
        {
            get { return typeof(WcfAuditBehavior); }
        }
    }
    public class WcfAuditBehavior : IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            
        }   

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            ChannelDispatcher channelDispatcher = endpointDispatcher.ChannelDispatcher;
            if (channelDispatcher != null)
            {
                foreach (EndpointDispatcher ed in channelDispatcher.Endpoints)
                {
                    ed.DispatchRuntime.MessageInspectors.Add(new WcfAuditMessageInspector());
                }
            }
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }
    }

 

---

app.config은 첨부 합니다.

첨부.txt
0.01MB