Useful WCF Behaviors-ierrorhandler

Source: Internet
Author: User
Tags stack trace

Behaviors in WCF is so stinking useful, and once you get past the basics of WCF they ' re arguably a necessity. Microsoft have saved itself from hundreds of hours of cursing by including the ability to define custom behaviors.

My favorite use of behaviors are addressing some cross cutting concerns that we consistently has in our WCF services. Specifically logging, service registration, WSDL tweaking, and error handling. Which brings us around to the Ierrorhandler interface.

Implementing Ierrorhandler "allows an implementer to control the fault message returned to the caller and optionally PERFO RM custom error processing such as logging ". Thank you MSDN. Ierrorhandler has a methods to Implement:handleerror, and Providefault. Implement them so, they do, they say they do. HandleError should do something with the error (in our case, we log it) and Providefault should return a fault message.

#region Ierrorhandler members//HandleError. Log an error, and then allow the error to being handled as usual.//Return true if the error is considered as already HANDLEDPUBL IC bool HandleError (Exception error) {try {\\our loggin service loggerclient logger = new Loggerclien        T (Basic, logaddress);        \\build Log message StringBuilder err = new StringBuilder (); Err. Appendline ("Source:" + error.)        Source); Err. Appendline ("Target:" + error.)        Targetsite.tostring ()); Err. Appendline ("Message:" + error.)        Message); Err. Appendline ("Stack Trace:" + error.)           Stacktrace.tostring ());        Customlogentry log = new Customlogentry (); Log.        Appdomainname = AppDomain.CurrentDomain.FriendlyName; Log.        EventId = 900; Log.        Eventidspecified = true; Log.        MachineName = Environment.MachineName; Log. Message = Err.        ToString (); Log.        Priority = 1; Log.        Priorityspecified = true; Log.    Severity = Traceeventtype.error;    Log.        Severityspecified = true; Log. Title = "Exception Caught:" + error.         Message; Logger.         log (log);    return true;    } catch (Exception) {throw new Exception ("Error in the handler"); }} public void Providefault (Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault) {//Shield the unknown exception faultexception faultexception = new Fa Ultexception (Error.    Message);    Messagefault Messagefault = Faultexception.createmessagefault (); Fault = Message.createmessage (version, Messagefault, faultexception.action);} #endregion

Pretty straight forward.

Now we just has to figure out a-from-a-to-get this-to-apply to our service, preferably-without a lot of extra work. So we don ' t want to go mucking around with attributes or anything else we had to remember to stick in as we ' re writing th E code. That's where behaviors come in. You can apply them via the config file.

We know we want this particular behavior to apply the entire service, so we want to implement IServiceBehavior in our C Lass along with Ierrorhandler.  IServiceBehavior has four methods that we had to implement, but fortunately we can ignore three of them. The one we care on this case is ApplyDispatchBehavior, where we'll apply our error handler to each of the channels In the service. The example below ErrorHandler is the name of the class we are implementing. Inventive name, isn ' t it?

public void ApplyDispatchBehavior (ServiceDescription servicedescription, ServiceHostBase servicehostbase) {    Ierrorhandler ErrorHandler = new ErrorHandler ();     foreach (Channeldispatcherbase channeldispatcherbase in servicehostbase.channeldispatchers)    {        ChannelDispatcher ChannelDispatcher = channeldispatcherbase as ChannelDispatcher;        CHANNELDISPATCHER.ERRORHANDLERS.ADD (ErrorHandler);    } }

Great, that's done. Now there's only one thing. We need a class, inherits from Behaviorextensionelement so, we can add our behavior via configuration. Fortunately Behaviorextensionelement is a breeze to implement. You need to impelement Behaviortype which just returns the type of your just implement IServiceBehavior class (Errorhandle R above), and Createbehavior which returns an instantiation of the class.

Class errorhandlerbehavior:behaviorextensionelement{public    override Type Behaviortype    {        get        {            return typeof (ErrorHandler);        }    }     protected override Object Createbehavior ()    {        return new ErrorHandler ();    }}

Now the code was done. The last thing to does is to apply the newly created behavior in the config file. Add our new behaviorextensionelement to the behaviorextensions sections, and then specify it in the Servicebehaviors sectio N. One important caveat, if Includeexceptiondetailinfaults is set to True, then the exception shielding (and I believe ERR or handling) won't work.

<system.serviceModel> <extensions> <behaviorExtensions> <add name= "errorlogging" type= "Errorhandlerbehavior, Errorhandling, version=1.0.0.0, culture=neutral, publickeytoken=8746502a48718374"/> </ behaviorextensions> </extensions> <bindings> <basicHttpBinding> <binding name= "b Asicbinding "> </binding> </basicHttpBinding> </bindings> <services> < Service behaviorconfiguration= "Service1behavior" name= "service" > <endpoint address= "binding=" Basichttpbindi Ng "bindingconfiguration=" basicbinding "contract=" Service "/> </service> </services> <behavi ors> <serviceBehaviors> <behavior name= "Service1behavior" > <servicemetadata httpget Url= "" httpgetenabled= "true"/> <servicedebug includeexceptiondetailinfaults= "false"/> <Err orlogging/> &Lt;/behavior> </serviceBehaviors> </behaviors> </system.serviceModel> 

There you go. Apply the Your WCF services and you won ' t has to re-invent the wheel again.

Useful WCF Behaviors-ierrorhandler

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.