C # use WCF to create a network-oriented service program

If that.

This kind of thing based on Microsoft's set of things, be used within the .NET particularly convenient. Weigh the pros and cons themselves, whether to use discretion.

Step 1, create a set of methods published online

  New Project, select the type "WCF Service Application"

  

 

   In the project, you can add any c # methods, such as:

  

 

   Note: All methods must have an interface description file, otherwise it can not be published. It will be mentioned later.

  So far, user-defined method to complete. "Debugging" can be published in iisexpress:

  

 

   Browser to access the situation as shown below:

  

 

   So far, the service publishing success. Of course, officially released by iis real case is the most common way.

Step 2, calling wcf service.

  Core: any new project, refer to this service, create a client, call it.

  

 

   Enter the url, go to:

  

 

   Here are several ways to see provided as a service. Namespace can use the default "ServiceReference1"

  Add the necessary reference to the main program  

1 using ConsoleApp1.ServiceReference1;

  The program can use these methods of  

1 static void Main(string[] args)
2         {
3             Service1Client sc = new Service1Client();
4             int x = 5;
5             x = sc.doubleX(5);
6             Console.WriteLine(x);
7             Console.ReadKey();
8         }

  运行结果:

  

 

 注意:要发布的方法,一定要在接口文件(本例为IService1.cs)里加以说明:

 1 public interface IService1
 2     {
 3 
 4         [OperationContract]
 5         string GetData(int value);
 6         [OperationContract]
 7         int doubleX(int x);
 8         [OperationContract]
 9         CompositeType GetDataUsingDataContract(CompositeType composite);
10 
11         // TODO: 在此添加您的服务操作
12     }

再次强调,这种服务通常使用iis发布,可以提供更加灵活的调用。相比于webapi,编写和调用习惯都更贴近于常规的c#程序。

缺点:一般仅提供给c#项目。

这种用法,类似于webapi,很贴近于MVC架构里的C。

典型用途:在数据库服务器上做一个wcf程序,可以为数据库应用做一次封装。无论是把access变成“网络数据库”;还是把网络数据库的网络访问权限关闭,仅靠wcf提供服务,以提高安全性,都可以。

Guess you like

Origin www.cnblogs.com/wanjinliu/p/11968281.html