A preliminary study of WCF -20:WCF Error protocol

Source: Internet
Author: User

WCF Error Contract Overview

    • In all managed applications, processing errors are represented by the Exception object. In SOAP-based applications, such as WCF applications, the service method uses a SOAP fault message to pass processing error messages. A SOAP fault is a message type that is included in the service operation metadata and therefore creates an error contract that the client can use to make the operation more reliable or more interactive. In addition, because SOAP faults are represented in XML format on the client, this is an excellent interoperability type system that can be used by clients on any SOAP platform, increasing the scope of application of WCF applications.
    • Because WCF applications can run under two types of error systems, any managed exception information that is sent to the client must be converted from an exception to a SOAP fault on the service and converted from a SOAP fault to an error exception in the WCF client. For duplex clients, the client contract can also send a SOAP fault back to the service. In either case, you can use the default service exception behavior, or you can explicitly control whether (and how) the exception is mapped to an error message.
    • There are two types of SOAP faults that can be sent: declared and undeclared. A declared SOAP fault is an error in which an operation has the System.ServiceModel.FaultContractAttribute property, which specifies the type of the custom SOAP fault. An undeclared SOAP fault is an error that is not specified in the contract of the operation.

Create an error contract

    • To implement error contracts to the client, you first need to servicebehaviorattribute.includeexceptiondetailinfaults or The Servicedebugbehavior.includeexceptiondetailinfaults is set to True (can be specified in the service configuration file).
    • When defining an error contract, we are usually displaying a custom error message. Usually we define the error message that needs to be displayed as a data contract, and then use Faultcontractattribute to make the error of which type of data contract is marked on the operation contract.
    • When a managed exception occurs during the operation, Faultexception<tdetail> is thrown (the type parameter is a serializable error message). The WCF client application renders the same type of SOAP fault that is thrown in the client implementation, that is, the faultexception<tdetail> (where the type parameter is serializable error information). Faultcontractattribute can only be used to specify SOAP faults for bidirectional service operations and asynchronous operations, and a one-way operation does not support SOAP faults and therefore Faultcontractattribute is not supported.

WCF example of an error contract

    • The solution structure is as follows:

  

    • Engineering Structure Description:
    1. Service: Class Library program, WCF server-side program. The data contract faultmessage is defined in the service contract interface ISampleService.cs to display the time and information for the error, and on the operation contract SampleMethod we use Faultcontract to mark the type of the error contract as Faultmessage. In implementing the Operation contract method SampleMethod, we can use faultexception<faultmessage> to customize the error and throw the custom exception information. The client takes advantage of detail in faultexception<faultmessage> to get an object that contains detailed error information. The code for ISampleService.cs is as follows:
usingSystem.ServiceModel;usingSystem.Runtime.Serialization;namespaceservice{[ServiceContract] Public InterfaceIsampleservice {[OperationContract] [Faultcontract (typeof(Faultmessage))] stringSampleMethod (stringmsg); } [DataContract] Public classFaultmessage {Private string_errortime; Private string_errormessage; [DataMember] Public stringErrortime {Get{return  This. _errortime;} Set{ This. _errortime =value;} } [DataMember] Public stringerrormessage {Get{return  This. _errormessage;} Set{ This. _errormessage =value;} }         PublicFaultmessage (stringTimestringmessage) {             This. _errortime =Time ;  This. _errormessage =message; }    }}

The code for SampleService.cs is as follows:

usingSystem.ServiceModel;namespaceservice{ Public classSampleservice:isampleservice { Public stringSampleMethod (stringmsg) {            if(Msg. Length <Ten)            {                return "the string entered is"+msg; }            Else            {                Throw NewFaultexception<faultmessage>(                    NewFaultmessage ("Error Time:"+ System.DateTime.Now.ToString (),"the input ""+ msg +""string greater than 10 characters")); }        }    }}

  

2. Host: Console application, service hosting program. To add a reference to the assembly service, complete the following code, the Homestay service. The Program.cs code is as follows:

  
usingSystem;usingSystem.ServiceModel;usingService;namespacehost{classProgram {Static voidMain (string[] args) {            using(ServiceHost host =NewServiceHost (typeof(Sampleservice))) {host.} Opened+=Delegate{Console.WriteLine ("Service has been started, press any key to terminate! ");                }; Host.                Open ();            Console.read (); }        }    }}
View Code

The app. Config code is as follows:

  
<?xml version="1.0"?><configuration> <system.serviceModel> <services> <service name="Service.sampleservice"behaviorconfiguration="Mexbehavior"> "http://localhost:1234/SampleService/"/> </baseAddresses> ""binding="Wshttpbinding"contract="Service.isampleservice"/> <endpoint address="Mex"binding="mexhttpbinding"contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Mexbehavior"> <servicemetadata httpgetenabled="true"/> <servicedebug includeexceptiondetailinfaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.servi Cemodel></configuration>
View Code

We generate client proxy classes and client configuration files through the SvcUtil.exe tool

SvcUtil.exe is a command-line tool that is located under Path C:\Program Files (x86) \microsoft Sdks\windows\v7.0a\bin, and we can run the tool from the command line to generate the client proxy class

    • Enter CMD in the run Open command line, enter CD C:\Program Files (x86) \microsoft Sdks\windows\v7.0a\bin
    • Input svcutil.exe/out:f:\ Sampleserviceclient.cs/config:f:\app.config Http://localhost:1234/SampleService

3. Client: A console application that invokes the program. Copy the generated UserInfoClient.cs and app. Config to the client's project directory and complete the calling code. The code for Program.cs is as follows:

usingSystem;usingSystem.ServiceModel;usingService;namespaceclient{classProgram {Static voidMain (string[] args) {Sampleserviceclient Proxy=Newsampleserviceclient (); Try{Console.WriteLine (proxy. SampleMethod ("WCF")); Console.WriteLine (proxy. SampleMethod ("Windows Communication Foundation")); }            Catch(faultexception<faultmessage>ex) {Console.WriteLine (ex. Detail.errortime+"\ n"+Ex.            Detail.errormessage); }            finally{console.read (); }        }    }}

The results of the program run as follows:

  

Summary

    • Usually we throw exception information through faultexception on the server, and then we can process it on the client, even if we don't add the faultcontract feature. Reference:WCF primary -12: WCF client exception handling
    • We can also set the includeexceptiondetailinfaults of the service to True (by default, false) by adding the ServiceBehavior attribute, and the client can also catch the thrown non-faultexception exception information. However, the exception will still cause the channel to appear to be wrong.
    • In this example, we implemented a custom error message operation for the error contract. One of the most important faultexception<tdetail> through the tdetail type, we can serialize and deserialize the custom data contract error information on the client side of the server, and finally implement the transmission of the error message of the SOAP message.

A preliminary study of WCF -20:WCF Error protocol

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.