首页 » 后端 » WCF由.Net Framework迁移到.Net Core的日志及证书问题

WCF由.Net Framework迁移到.Net Core的日志及证书问题

 

日志记录

旧代码:

    public class TraceExtension : SoapExtension
    {
        Stream _oldStream;
        Stream _newStream;

        public override Stream ChainStream(Stream stream)
        {
            _oldStream = stream;
            _newStream = new MemoryStream();
            return _newStream;
        }

        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }

        public override object GetInitializer(Type WebServiceType)
        {
            return null;
        }

        public override void Initialize(object initializer)
        {

        }

        public override void ProcessMessage(SoapMessage message)
        {
            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    //TestRequest(message);
                    break;
                case SoapMessageStage.AfterSerialize:
                    WriteRequest(message);
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    WriteResponse(message);
                    break;
                case SoapMessageStage.AfterDeserialize:
                    break;
                default:
                    throw new Exception("invalidstage");
            }
        }

        public void WriteRequest(SoapMessage message)
        {
            try
            {
                _newStream.Position = 0;

                TextReader reader = new StreamReader(_newStream);
                string methodName = message.MethodInfo.ToString();
                string reqLog = reader.ReadToEnd();

                //@@ Async log
                Task t = Task.Factory.StartNew(() =>
                {
                    try
                    {

                        WebSvcLogger.Logger.Information(string.Format("API - \"{0}\" Request:\r\n{1}", methodName, reqLog));
                    }
                    catch
                    {
                        //Log Failed
                    }
                });
            }
            catch
            {
                //Log Failed
            }
            finally
            {
                _newStream.Position = 0;
                Copy(_newStream, _oldStream);
            }
        }

        public void WriteResponse(SoapMessage message)
        {
            try
            {
                Copy(_oldStream, _newStream);
                _newStream.Position = 0;

                TextReader reader = new StreamReader(_newStream);
                string methodName = message.MethodInfo.ReturnType.FullName;                
                string respLog = reader.ReadToEnd();

                //Async run
                Task t = Task.Factory.StartNew(() =>
                {                    
                    WebSvcLogger.Logger.Information(string.Format("API - \"{0}\" Response:\r\n{1}", methodName, respLog));
                });
            }
            catch
            {
                //Log Failed
            }
            finally
            {
                _newStream.Position = 0;
            }
        }

        void Copy(Stream from, Stream to)
        {
            TextReader reader = new StreamReader(from);
            TextWriter writer = new StreamWriter(to);
            writer.WriteLine(reader.ReadToEnd());
            writer.Flush();
        }
    }

    [AttributeUsage(AttributeTargets.Method)]
    public class TraceExtensionAttribute : SoapExtensionAttribute
    {
        private int priority;

        public override Type ExtensionType
        {
            get { return typeof(TraceExtension); }
        }

        public override int Priority
        {
            get { return priority; }
            set { priority = value; }
        }
    }

新代码:

    public class HttpProtocol : IClientMessageInspector
    {

        private readonly string _serviceName;
        public HttpProtocol(string serviceName)
        {
            _serviceName = serviceName;
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            var buffer = reply.CreateBufferedCopy(Int32.MaxValue);
            reply = buffer.CreateMessage();

            WriteResponse(buffer.CreateMessage().CreateBufferedCopy(Int32.MaxValue));
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();

            WriteRequest(buffer.CreateMessage().CreateBufferedCopy(Int32.MaxValue));
            return null;
        }
        public Message WriteRequest(MessageBuffer buffer)
        {
            Message msg = buffer.CreateMessage();
            StringBuilder sb = new StringBuilder();
            sb.Append(msg.ToString());

            string reqLog = sb.ToString();

            //@@ Async log
            Task t = Task.Factory.StartNew(() =>
            {
                try
                {

                    WebSvcLogger.Logger.Information(string.Format("API - \"{0}\" Request:\r\n{1}", _serviceName, reqLog));
                }
                catch
                {
                    //Log Failed
                }
            });
            return buffer.CreateMessage();
        }

        public Message WriteResponse(MessageBuffer buffer)
        {
            Message msg = buffer.CreateMessage();
            StringBuilder sb = new StringBuilder();
            sb.Append(msg.ToString());

            string respLog = sb.ToString();

            //Async run
            Task t = Task.Factory.StartNew(() =>
            {
                WebSvcLogger.Logger.Information(string.Format("API - \"{0}\" Response:\r\n{1}", _serviceName, respLog));
            });
            return buffer.CreateMessage();
        }
        private static Message Clone(Message message)
        {
            return message.CreateBufferedCopy(int.MaxValue).CreateMessage();
        }
    }

    public class TraceMessageBehavior : IEndpointBehavior
    {
        private readonly string _serviceName;
        public TraceMessageBehavior(string serviceName)
        {
            _serviceName = serviceName;
        }

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        { }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.ClientMessageInspectors.Add(new HttpProtocol(_serviceName));
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {

        }

        public void Validate(ServiceEndpoint endpoint)
        { }
    }

证书问题

旧方法:

    SearchServiceBinding client = new SearchServiceBinding();
    client.Url = "http://localhost/";

    //Set Basic Auth Authorization
    client.Credentials = new NetworkCredential(config.Username, config.Password);

    // Send the request
    var resp = client.service(req);

    return resp;

新方法:

    var binding = new BasicHttpBinding();
    binding.Security.Mode = BasicHttpSecurityMode.Transport;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    var address = "http://localhost/";

    ServicePortTypeClient client = new ServicePortTypeClient(binding, address);
    client.Endpoint.EndpointBehaviors.Add(new TraceMessageBehavior("Search"));

    //Set Basic Auth Authorization
    client.ClientCredentials.UserName.UserName = config.Username;
    client.ClientCredentials.UserName.Password = config.Password;

    // Send the request
    var resp = await client.serviceAsync(req);

    return resp;

原文链接:WCF由.Net Framework迁移到.Net Core的日志及证书问题,转载请注明来源!