WCF(二) 使用配置文件实现WCF应用程序

时间:2023-03-09 02:56:42
WCF(二) 使用配置文件实现WCF应用程序

服务三要素ABC
A:Address 在哪里 (包含传输方式的信息)
B:Binding 怎么实现(与地址的传输方式要匹配)
C:Contract做什么(服务契约)

WCF(二) 使用配置文件实现WCF应用程序

WCF(二) 使用配置文件实现WCF应用程序

namespace WCFServiceDemo
{
[ServiceContract]
public interface IHelloService
{
[OperationContract]
DateTime GetDateTime(); [OperationContract]
DataTable GetUserInfo();
}
}

继承接口

 class HelloService:IHelloService
{
public DateTime GetDateTime()
{
return DateTime.Now;
} public DataTable GetUserInfo()
{
string connstring = @"Data Source=WIN7U-20130122R\SQLEXPRESS;Initial Catalog=TCEKT;Persist Security Info=True;User ID=sa";
SqlConnection conn = new SqlConnection(connstring);
SqlDataAdapter sda=new SqlDataAdapter("select * from User",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}

Winfom调用

    public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ServiceHost host = null;
private void button1_Click(object sender, EventArgs e)
{
host = new ServiceHost(typeof(WinformHello.HelloService));
host.Open();
label1.Text = "服务已启动!";
}
}

配置文件App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<!--WCF-->
<system.serviceModel>
<services>
<service name="WinformHello.HelloService" behaviorConfiguration="testBehavior"><!--name:指实现服务契约的类-->
<host>
<baseAddresses>
<add baseAddress="http://localhost:8001/Hello"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="WCFServiceDemo.IHelloService">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="testBehavior">
<serviceMetadata httpGetEnabled="true"/><!--允许访问wcf服务-->
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

启动:

WCF(二) 使用配置文件实现WCF应用程序

因win7安全性问题,如果启动不了 vs2012 右键

WCF(二) 使用配置文件实现WCF应用程序

如果启动成功

在app.config文件中找到

<baseAddresses>
<add baseAddress="http://localhost:8001/Hello"/>
</baseAddresses>

Ctrl键+左击单击

WCF(二) 使用配置文件实现WCF应用程序

OK  成功……

--学云网Tiger老师的视频