生成两个证书:
makecert 命令参考:证书创建工具 (Makecert.exe)
certmgr命令参考: 证书管理器工具 (Certmgr.exe)
makecert -sr CurrentUser -ss My -a sha1 -n CN=localhost -sky exchange -pe
certmgr.exe -add -r CurrentUser -s My -c -n localhost -r CurrentUser -s TrustedPeople
makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WCFUser -sky exchange -pe
certmgr.exe -add -r CurrentUser -s My -c -n WCFUser -r CurrentUser -s TrustedPeople
通过证书管理工具可以看到刚才生成的证书
在服务端添加证书:
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace ExchangeService
{
public class Program
{
public static void Main(string[] args)
{
Uri address = new Uri("http://localhost:8001/TradeService");
WSHttpBinding binding = new WSHttpBinding();
Type contract = typeof(ExchangeService.ITradeService);
ServiceHost host = new ServiceHost(typeof(TradeService));
host.AddServiceEndpoint(contract, binding, address);
// Add Auditing to the service
ServiceSecurityAuditBehavior auditProvider =
host.Description.Behaviors.Find<ServiceSecurityAuditBehavior>();
if (auditProvider == null)
{
auditProvider = new ServiceSecurityAuditBehavior();
}
auditProvider.AuditLogLocation = AuditLogLocation.Application;
auditProvider.MessageAuthenticationAuditLevel =
AuditLevel.SuccessOrFailure;
auditProvider.ServiceAuthorizationAuditLevel =
AuditLevel.SuccessOrFailure;
host.Description.Behaviors.Add(auditProvider);
host.Open();
Console.WriteLine("The WCF Management trading service is available.");
Console.ReadKey();
}
}
}
客户端:
using System;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Threading;
namespace ExchangeService
{
class Program
{
static void Main( string[] args )
{
EndpointAddress address =
new EndpointAddress("http://localhost:8001/TradeService");
WSHttpBinding binding = new WSHttpBinding();
System.ServiceModel.ChannelFactory<ITradeService> cf =
new ChannelFactory<ITradeService>(binding, address);
ITradeService proxy = cf.CreateChannel();
Console.WriteLine("\nTrade IBM");
try
{
double result = proxy.TradeSecurity("IBM", 1000);
Console.WriteLine("Cost was " + result);
Console.WriteLine("\nTrade MSFT");
result = proxy.TradeSecurity("MSFT", 2000);
Console.WriteLine("Cost was " + result);
}
catch (Exception ex)
{
Console.Write("Can not perform task. Error Message - " + ex.Message);
}
Console.WriteLine("\n\nPress <enter> to exit...");
Console.ReadLine();
}
}
}