1、新建一个WCF Service Library项目,名字叫做WCFServiceLibrary1,代码就用默认的,以下是它的两个方法:
public string MyOperation1(string myValue)
public string MyOperation2(DataContract1 dataContractValue)
2、在WCFServiceLibrary1项目下新建一个类文件,名字叫做MyCustomValidator.cs,编写如下代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
namespace WCFServiceLibrary1{
public class MyCustomValidator:UserNamePasswordValidator{
public override void Validate(string userName, string password)
{
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
if (userName != "123456" || password != "123456")
throw new Exception("用户名和密码错误");
else
throw new Exception("用户名和密码不能为空");
}
} //为了节约地方,就这么堆起了
3、新建一个WCFService项目,名字是WCFService1,引用前面已经编译好的WCFServiceLibrary1.dll,打开Service.svc
写入以下代码:
<% @ServiceHost Language=C# Debug="true" Service="WCFServiceLibrary1.service1" CodeBehind="" %>
使用Makecert 工具创建一个证书,命令如下:
Makecert -r -pe -n "CN=MyServer" -ss My -sky exchange
4、Web.Config做如下配置,并运行WCFService项目:
<system.serviceModel>
<services>
<service behaviorConfiguration="MyBehavior" name="WCFServiceLibrary1.service1">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="myBinding"
contract="WCFServiceLibrary1.IService1" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehavior">
<serviceCredentials>
<serviceCertificate findValue="MyServer" storeName="My" x509FindType="FindBySubjectName" />
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="WCFServiceLibrary1.MyCustomValidator,WCFServiceLibrary1" />
</serviceCredentials>
<serviceDebug httpsHelpPageEnabled="false" />
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="myBinding">
<security>
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
6、使用svcutil.exe 工具生成客户端配置文件和代理类,使用方法:
svcutil.exe http://localhost:4207/WCFService1/Service.svc?wsdl
7、新建一个Windows程序,叫做WindowsApplication1,首先添加如下引用:
System.ServiceModel
System.Runtime.Serialization
8、将前面生成的配置文件中的节点Copy到App.Config中,将代理类复制到WindowsApplication1下,在窗体上增加一个按钮,并写入下面的代码:
private void button1_Click(object sender, EventArgs e)
{
Service1Client client = new Service1Client();
client.ClientCredentials.UserName.UserName = "123456";
client.ClientCredentials.UserName.Password = "123456";
MessageBox.Show(client.MyOperation1("www.xt80.com"));
}
运行WindowsApplication1,将会看到返回信息:Hello:www.xt80.com
| 昵称 密码 游客无需密码 |
| 网址 电邮 注册 |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |







