Preliminary Study on WCF-20: WCF error protocol, Preliminary Study on wcf-20 Protocol

Source: Internet
Author: User

Preliminary Study on WCF-20: WCF error protocol, Preliminary Study on wcf-20 Protocol
WCFError agreements Overview

 

  • In all hosted applications, error handling is represented by an Exception object. In SOAP-based applications (such as WCF applications), service methods use SOAP error messages to transmit and process error messages. A soap error is a message type included in the service operation metadata. Therefore, an error protocol is created, which can be used by the client to make the operation more reliable or interactive. In addition, because SOAP errors are expressed in XML format on the client, this is an excellent type system that can be used by clients on any SOAP platform, you can increase the applicability of the WCF application.
  • Since both types of error systems can run a WCF application, any hosted exception information sent to the client must be converted from an exception to a SOAP error on the service, an exception occurred while converting SOAP errors to errors in the WCF client. For duplex clients, the client protocol can also send SOAP errors back to the service. In either case, you can use the default service exception behavior, or explicitly control whether (and how) to map exceptions to error messages.
  • You can send two types of SOAP errors: declared and undeclared. Declared SOAP errors refer to errors in which an operation has the System. ServiceModel. FaultContractAttribute attribute (used to specify the custom SOAP error type. SOAP errors that are not declared are not specified in the operation protocol.

 

Create error agreements

 

  • To Implement error protocols to the client, you must first set ServiceBehaviorAttribute. IncludeExceptionDetailInFaults or ServiceDebugBehavior. IncludeExceptionDetailInFaults to true (which can be specified in the service configuration file ).
  • When defining error agreements, we usually display custom error messages. Generally, we define the error information to be displayed as a data protocol, and then use FaultContractAttribute to mark the type of a data protocol error on the operation agreement.
  • FaultException <TDetail> is triggered when a hosting exception occurs during the operation (the type parameter is a serialized error message ). The SOAP Error Type presented by the WCF client application is the same as that caused by the client implementation, that is, FaultException <TDetail> (the type parameter here is a serialized error message ). FaultContractAttribute can only be used to specify SOAP Errors for Bidirectional service operations and asynchronous operations. Unidirectional operations do not support SOAP errors and therefore do not support FaultContractAttribute.

 

WCF Error Protocol example

 

  • The solution structure is as follows:

  

  • Engineering Structure Description:
using System.ServiceModel;using System.Runtime.Serialization;namespace Service{    [ServiceContract]    public interface ISampleService    {        [OperationContract]        [FaultContract(typeof(FaultMessage))]        string SampleMethod(string msg);    }    [DataContract]    public class FaultMessage    {        private string _errorTime;        private string _errorMessage;        [DataMember]        public string ErrorTime        {            get { return this._errorTime; }            set { this._errorTime = value; }        }        [DataMember]        public string ErrorMessage        {            get { return this._errorMessage; }            set { this._errorMessage = value; }        }        public FaultMessage(string time,string message)        {            this._errorTime = time;            this._errorMessage = message;        }    }}

The sample service. cs code is as follows:

Using System. serviceModel; namespace Service {public class SampleService: ISampleService {public string SampleMethod (string msg) {if (msg. length <10) {return "the input string is" + msg;} else {throw new FaultException <FaultMessage> (new FaultMessage ("error time:" + System. dateTime. now. toString (), "input [" + msg + "] string greater than 10 characters "));}}}}

  

2. Host: console application and service bearer program. Add a reference to the Assembly Service. Complete the following code to host the Service. The Program. cs code is as follows:

Using System; using System. serviceModel; using Service; namespace Host {class Program {static void Main (string [] args) {using (ServiceHost host = new ServiceHost (typeof (SampleService) {host. opened + = delegate {Console. writeLine ("the 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 "> The svcutil.exe tool is used to generate the client proxy class and client configuration file.

Svcutil.exe is a command line tool located in the path C: \ Program Files (x86) \ Microsoft SDKs \ Windows \ v7.0A \ Bin. You can run the command line tool to generate a client proxy class.

  • Run cmd to open the command line and 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: console application and Client calling program. Copy the generated UserInfoClient. cs and App. config to the Client project directory to complete the Client call code. The Code of Program. cs is as follows:

using System;using System.ServiceModel;using Service;namespace Client{    class Program    {        static void Main(string[] args)        {            SampleServiceClient proxy = new SampleServiceClient();            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 program running result is as follows:

  

 

Summary

 

  • Usually we throw exception information through FaultException on the server end, and then we can process it on the client, even if we do not add the FaultContract feature. Refer:WCFPreliminary Study-12: WCFClient Exception Handling
  • You can also set IncludeExceptionDetailInFaults of the Service to true (false by default) by adding the ServiceBehavior feature. The client can also capture the thrown non-FaultException exception information, however, this exception still causes channel errors.
  • In this example, we implement the custom error message operation of the error agreement. Among them, the most important FaultException <TDetail>. With the TDetail type, we can serialize and deserialize Custom Data Protocol Error messages on the server client, finally, the error message of the SOAP message is transmitted.

Related Article

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.