Create and call a WCF Service.

Source: Internet
Author: User

Create and call a WCF Service.

I am familiar with and familiar with WCF because I have never been familiar with it. I have heard too much about it. Today I took some time to read it, I also wrote a small WCF program and called it. Steps:

1. Create a solution WCF and a console project WCFTestService (this is the WCF Service)

2. Configure the App. Config of the WCF Service

3. Write the WCF Service Code

4. Create the WCFTestClient project to test the access service)

5. Write client code

6. Execute the Access Service

The following describes the operations and code of each step in detail:

1. Create a solution WCF and a console project WCFTestService (this is the WCF Service)

This step is the foundation and will certainly be created, so it will not be cumbersome. 10 thousand words are omitted here ··········

2. Configure the App. Config of the WCF Service

First, I first paste the content of the App. Config.

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <startup> <supportedRuntime version = "v4.0" sku = ". NETFramework, Version = v4.5 "/> </startup> <system. serviceModel> <serviceHostingEnvironment identifier = "true"/> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name = "" maxcompute edmessagesize = "300000000" identifier = "Json" helpEnabled = "true" automaticFormatSelectionEnabled "true"> <readerQuotas MaxArrayLength = "30000000"/> </standardEndpoint> </webHttpEndpoint> </standardEndpoints> <bindings> <webHttpBinding> <binding name = "webHttpBindingConfig" sendTimeout = "00:10:00" timeout =" false "maxcompute edmessagesize =" 2147483646 "> <readerQuotas maxStringContentLength =" 2147483646 "maxArrayLength =" 2147483646 "/> </binding> </webHttpBinding> </bindings> <services> <! -- Note: the service name must match the service implementation name. --> <Service name = "WCFTestService. DbApiInfo" behaviorConfiguration = "RestServiceBehavior"> <! -- Note: The service must have an http base address to add this endpoint. --> <Host> <baseAddresses> <add baseAddress =" http://localhost:8888/Service/DbApiInfo "/> </BaseAddresses> After carefully observing this code, you will find that the content of App. Config is one more node than the newly generated App. Config <system. serviceModel> </system. serviceModel>

And it contains big content.

<System. serviceModel> </system. serviceModel> is the service configuration content.

The most important thing is the node <services> </services> in <system. serviceModel> </system. serviceModel>, which is the focus of service configuration,

There are two <service> </service> nodes in this node. Each <service> </service> node is a configuration service.

The following figure shows a <service> </service> node:

<! -- Note: the service name must match the service implementation name. --> <Service name = "WCFTestService. DbApiInfo" behaviorConfiguration = "RestServiceBehavior"> <! -- Note: The service must have an http base address to add this endpoint. --> <Host> <baseAddresses> <add baseAddress = "http: // localhost: 8888/Service/DbApiInfo"/> </baseAddresses> 

Name = "WCFTestService. DbApiInfo": as the name suggests, it is the service name. Different service names must be different. WCFTestService is the namespace

<Add baseAddress = "http: // localhost: 8888/Service/DbApiInfo"/>: the Service access address.

Contract = "WCFTestService. IApiInfo">: indicates the service interface. WCFTestService is the namespace

Note: each time you want to add a service, you can create a node <service> </service> and modify the names of the preceding three nodes so that the configuration file is OK.

When there are no other special requirements, the configuration file does not need to be modified elsewhere. Since it is just a simple WCF test service, I will not say anything else, so as not to be cumbersome.

3. Write the WCF Service Code

Compile the WCF code in three steps:

(1) Add an interface corresponding to the service: for example, the interface corresponding to the service "WCFTestService. DbApiInfo": IApiInfo (that is, the name of the interface mentioned above must be consistent with that mentioned above)

[ServiceContract]    public interface IApiInfo    {        [OperationContract]        [ServiceKnownType(typeof(string))]        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]        string CreateApi(Stream name);    }

We have defined the [ServiceContract] label. This label indicates that this interface and the classes that implement this interface are Service Classes released externally. The [OperationContract] label is added to each method to be released externally, to allow external access to this method. One of the two tags is missing, and neither method can be accessed externally.
The [ServiceContract] and [OperationContract] labels need to be imported into the using System. ServiceModel namespace.

(2) Add the implementation class corresponding to the interface: DbApiInfo. cs

Public class DbApiInfo: IApiInfo {public string CreateApi (Stream name) {// name. position = 0; StreamReader reader = new StreamReader (name); string text = reader. readToEnd (); return "Your name is:" + text ;}}

(3) code for starting a service

The method to start the service is

Private static List <ServiceHost> _ LsSvcHost = new List <ServiceHost> ();
Public static void StartSvc () {try {ServicesSection servicesSection = ConfigurationManager. getSection ("system. serviceModel/services ") as ServicesSection; foreach (ServiceElement service in servicesSection. services) {Type serviceType = Type. getType (service. name); ServiceHost SvcHost = new ServiceHost (serviceType); string strLog = string. empty; SvcHost. opened + = delegate {Console. writeLine (string. format ("service [{0}] has been started. Public service addresses include:", service. name) ;}; SvcHost. open (); foreach (var endpoint in SvcHost. description. endpoints) {Console. writeLine (string. format ("Endpoint: {0}", endpoint. address. toString ();} // logger. info (strLog); _ LsSvcHost. add (SvcHost) ;}} catch (System. exception ex) {Console. writeLine ("Data Service Startup exception:", ex );}}

Then put the method in the main () function to call it:

static void Main(string[] args)        {            StartSvc();            Console.ReadKey();            foreach (ServiceHost SvcHosts in _LsSvcHost) SvcHosts.Close();        }

Start the service and you will see that the service has been started:

Because two services are configured in the configuration file, two services are started here (Note: After configuring the service, you must add the corresponding interfaces and interface implementation classes ).

4. Create the WCFTestClient project to test the access service)

It's easy to create a project. I just need to paste my interface (because it's a test, it's hard to see the interface, so sorry ····)

5. Write client code

This is mainly the Click Event of the write button "Get return value". First, paste the code and explain it:

Public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {}/// <summary> /// Based on the provided service address and passed parameter values, get the returned value /// </summary> /// <param name = "strUri"> service address </param> /// <param name = "strBody"> pass the Parameter value </param> /// <returns> </returns> public string PostHttp (string strUri, string strBody) {HttpWebRequest myRequest = (HttpWebRequest) WebReques T. Create (strUri); if (! String. IsNullOrEmpty (string. Empty )&&! String. isNullOrEmpty (string. empty) {myRequest. credentials = GetCredentialCache (strUri, string. empty, string. empty); myRequest. headers. add ("Authorization", GetAuthorization (string. empty, string. empty);} // converts it to a network stream byte [] buf = UnicodeEncoding. UTF8.GetBytes (strBody); // sets myRequest. method = "POST"; myRequest. contentLength = buf. length; myRequest. contentType = "application/x-www-form-urlencoded"; myRequest. keepAlive = false; myRequest. protocolVersion = HttpVersion. version10; // send the request Stream newStream = myRequest. getRequestStream (); newStream. write (buf, 0, buf. length); newStream. close (); // get the interface return value HttpWebResponse myResponse = (HttpWebResponse) myRequest. getResponse (); StreamReader reader = new StreamReader (myResponse. getResponseStream (), Encoding. UTF8); string strReturn = HttpUtility. htmlDecode (reader. readToEnd (); reader. close (); myResponse. close (); string p = @ "\/Date \ (\ d +) \ + \ d + \)\\/"; matchEvaluator evaluator = new MatchEvaluator (ConvertJsonDateToDateString); // process the time and reference the System. text. regularExpressions; namespace Regex reg = new Regex (p); strReturn = reg. replace (strReturn, evaluator); return strReturn;} private CredentialCache GetCredentialCache (string uri, string username, string password) {string authorization = string. format ("{0 }:{ 1}", username, password); CredentialCache credCache = new CredentialCache (); credCache. add (new Uri (uri), "Basic", new NetworkCredential (username, password); return credCache;} private string GetAuthorization (string username, string password) {string authorization = string. format ("{0 }:{ 1}", username, password); return "Basic" + Convert. toBase64String (new ASCIIEncoding (). getBytes (authorization);} private string ConvertJsonDateToDateString (Match m) // serialize the time {string result = string. empty; DateTime dt = new DateTime (1970, 1, 1); dt = dt. addMilliseconds (long. parse (m. groups [1]. value); dt = dt. toLocalTime (); result = dt. toString ("yyyy-MM-dd HH: mm: ss"); return result;} private void button#click (object sender, EventArgs e) {string strUri =" http://localhost:8888/Service/DbApiInfo/CreateApi "; String getstr = PostHttp (strUri," Andy Lau "); textBox1.Text = getstr ;}}View Code

 

PostHttp is a common method that can be called as a public method.

Click Event.

6. Execute the Access Service

In this case, we only need to run the service. when running the client, click the button to get the result returned by the Service.

So far, the establishment and call of a simple WCF Service have been completed ······

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.