Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6020825
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T03:37:27+00:00 2026-05-23T03:37:27+00:00

I have a WCF Service, And I inspect that using MessageInspector ( inherit IDispatchMessageInspector)

  • 0

I have a WCF Service, And I inspect that using MessageInspector ( inherit IDispatchMessageInspector)

I want to do some thing before running service and result of that ı want not run service.

I want to prevent client call but client dont receive exception.

Can you help me

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T03:37:28+00:00Added an answer on May 23, 2026 at 3:37 am

    This scenario looks like the post in the MSDN WCF forum entitled “IDispatchMessageInspector.AfterReceiveRequest – skip operation and manually generate custom response instead“. If this is what you need (when you receive a message in the inspector, you decide that you want to skip the service operation, but return a message to the client and the client should not see an exception), then this answer should work for you as well. Notice that you’ll need to create the response message in the same format as the client expects, otherwise you’ll have an exception.

    This code uses three of the (many) WCF extensibility points to achieve that scenario, a message inspector (as you’ve mentioned you’re using), a message formatter and an operation invoker. I’ve blogged about them in an ongoing series about WCF extensibility at http://blogs.msdn.com/b/carlosfigueira/archive/2011/03/14/wcf-extensibility.aspx.

    public class Post_55ef7692_25dc_4ece_9dde_9981c417c94a
    {
        [ServiceContract(Name = "ITest", Namespace = "http://tempuri.org/")]
        public interface ITest
        {
            [OperationContract]
            string Echo(string text);
        }
        public class Service : ITest
        {
            public string Echo(string text)
            {
                return text;
            }
        }
        static Binding GetBinding()
        {
            BasicHttpBinding result = new BasicHttpBinding();
            return result;
        }
        public class MyOperationBypasser : IEndpointBehavior, IOperationBehavior
        {
            internal const string SkipServerMessageProperty = "SkipServer";
            public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
            }
    
            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
            }
    
            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyInspector(endpoint));
            }
    
            public void Validate(ServiceEndpoint endpoint)
            {
            }
    
            public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
            {
            }
    
            public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
            {
            }
    
            public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
            {
                dispatchOperation.Formatter = new MyFormatter(dispatchOperation.Formatter);
                dispatchOperation.Invoker = new MyInvoker(dispatchOperation.Invoker);
            }
    
            public void Validate(OperationDescription operationDescription)
            {
            }
    
            class MyInspector : IDispatchMessageInspector
            {
                ServiceEndpoint endpoint;
                public MyInspector(ServiceEndpoint endpoint)
                {
                    this.endpoint = endpoint;
                }
    
                public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
                {
                    Message result = null;
                    HttpRequestMessageProperty reqProp = null;
                    if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
                    {
                        reqProp = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                    }
    
                    if (reqProp != null)
                    {
                        string bypassServer = reqProp.Headers["X-BypassServer"];
                        if (!string.IsNullOrEmpty(bypassServer))
                        {
                            result = Message.CreateMessage(request.Version, this.FindReplyAction(request.Headers.Action), new OverrideBodyWriter(bypassServer));
                        }
                    }
    
                    return result;
                }
    
                public void BeforeSendReply(ref Message reply, object correlationState)
                {
                    Message newResult = correlationState as Message;
                    if (newResult != null)
                    {
                        reply = newResult;
                    }
                }
    
                private string FindReplyAction(string requestAction)
                {
                    foreach (var operation in this.endpoint.Contract.Operations)
                    {
                        if (operation.Messages[0].Action == requestAction)
                        {
                            return operation.Messages[1].Action;
                        }
                    }
    
                    return null;
                }
    
                class OverrideBodyWriter : BodyWriter
                {
                    string bypassServerHeader;
                    public OverrideBodyWriter(string bypassServerHeader)
                        : base(true)
                    {
                        this.bypassServerHeader = bypassServerHeader;
                    }
    
                    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
                    {
                        writer.WriteStartElement("EchoResponse", "http://tempuri.org/");
                        writer.WriteStartElement("EchoResult");
                        writer.WriteString(this.bypassServerHeader);
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }
                }
            }
    
            class MyFormatter : IDispatchMessageFormatter
            {
                IDispatchMessageFormatter originalFormatter;
                public MyFormatter(IDispatchMessageFormatter originalFormatter)
                {
                    this.originalFormatter = originalFormatter;
                }
    
                public void DeserializeRequest(Message message, object[] parameters)
                {
                    if (message.Properties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
                    {
                        Message returnMessage = message.Properties[MyOperationBypasser.SkipServerMessageProperty] as Message;
                        OperationContext.Current.IncomingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage);
                        OperationContext.Current.OutgoingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage);
                    }
                    else
                    {
                        this.originalFormatter.DeserializeRequest(message, parameters);
                    }
                }
    
                public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
                {
                    if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
                    {
                        return null;
                    }
                    else
                    {
                        return this.originalFormatter.SerializeReply(messageVersion, parameters, result);
                    }
                }
            }
    
            class MyInvoker : IOperationInvoker
            {
                IOperationInvoker originalInvoker;
    
                public MyInvoker(IOperationInvoker originalInvoker)
                {
                    if (!originalInvoker.IsSynchronous)
                    {
                        throw new NotSupportedException("This implementation only supports synchronous invokers");
                    }
    
                    this.originalInvoker = originalInvoker;
                }
    
                public object[] AllocateInputs()
                {
                    return this.originalInvoker.AllocateInputs();
                }
    
                public object Invoke(object instance, object[] inputs, out object[] outputs)
                {
                    if (OperationContext.Current.IncomingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
                    {
                        outputs = null;
                        return null; // message is stored in the context
                    }
                    else
                    {
                        return this.originalInvoker.Invoke(instance, inputs, out outputs);
                    }
                }
    
                public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
                {
                    throw new NotSupportedException();
                }
    
                public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
                {
                    throw new NotSupportedException();
                }
    
                public bool IsSynchronous
                {
                    get { return true; }
                }
            }
        }
        public static void Test()
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), GetBinding(), "");
            endpoint.Behaviors.Add(new MyOperationBypasser());
            foreach (var operation in endpoint.Contract.Operations)
            {
                operation.Behaviors.Add(new MyOperationBypasser());
            }
    
            host.Open();
            Console.WriteLine("Host opened");
    
            ChannelFactory<ITest> factory = new ChannelFactory<ITest>(GetBinding(), new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();
            Console.WriteLine(proxy.Echo("Hello"));
    
            Console.WriteLine("And now with the bypass header");
            using (new OperationContextScope((IContextChannel)proxy))
            {
                HttpRequestMessageProperty httpRequestProp = new HttpRequestMessageProperty();
                httpRequestProp.Headers.Add("X-BypassServer", "This message will not reach the service operation");
                OperationContext.Current.OutgoingMessageProperties.Add(
                    HttpRequestMessageProperty.Name,
                    httpRequestProp);
                Console.WriteLine(proxy.Echo("Hello"));
            }
    
            ((IClientChannel)proxy).Close();
            factory.Close();
    
            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have WCF service running on netTcpBinding, everything fine I have some more functions
I have WCF Service that returns data as DataTable type. I want to insert
I have a WCF service that I have to reference from a .net 2.0
I have a WCF service and I want to expose it as both a
I have a WCF service running on the IIS with a ServiceHostFactory. It's running
I have a WCF service, hosted in IIS 7.0 that needs to run database
I have a WCF Service that should not enter the faulted state. If there's
I have a WCF service that is hosted in a windows application. The service
I have WCF service that is IIS-hosted and I have to send binary data
I have a WCF service that accepts requests from JQuery. Currently, I can access

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.