我是.net和Web服务的新手
可以在不添加服务引用的情况下通过证书使用Web服务c#/。net并设置安全性吗?
如果是,那么该怎么做
WCF还是WSE?
如何向其中添加安全策略?
我已经查看了官方文档中的WCF,httpclient,X509store,证书,WSE,但不知道通过代码申请。
我需要一个字符串响应
谢谢
添加服务引用通常用于生成客户端代理,而生成客户端代理可以通过使用通道工厂来完成。因此,根据您的要求,我们只需要创建一个WCF服务器端并使用证书对客户端进行身份验证,就足够了。客户端设法通过ChannelFactory调用服务,这是一个示例。服务器端(控制台应用程序)
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://localhost:21011");
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Message;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
using (ServiceHost sh = new ServiceHost(typeof(MyService), uri))
{
sh.AddServiceEndpoint(typeof(IService), binding, "");
ServiceMetadataBehavior smb;
smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
{
smb = new ServiceMetadataBehavior()
{
HttpGetEnabled = true
};
sh.Description.Behaviors.Add(smb);
}
sh.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "5ba5022f527e32ac02548fc5afc558de1d314cb6");
Binding mexbinding = MetadataExchangeBindings.CreateMexHttpBinding();
sh.AddServiceEndpoint(typeof(IMetadataExchange), mexbinding, "mex");
sh.Opened += delegate
{
Console.WriteLine("Service is ready");
};
sh.Closed += delegate
{
Console.WriteLine("Service is clsoed");
};
sh.Open();
Console.ReadLine();
//pause
sh.Close();
Console.ReadLine();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string Test();
}
public class MyService : IService
{
public string Test()
{
return DateTime.Now.ToLongTimeString();
}
}
在客户端,我们可以通过使用通道工厂来使用服务。
class Program
{
static void Main(string[] args)
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Message;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
Uri uri = new Uri("http://vabqia969vm:21011");
ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, new EndpointAddress(uri));
factory.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.Root, X509FindType.FindByThumbprint, "5ba5022f527e32ac02548fc5afc558de1d314cb6");
factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "f0969c5725b2f142b7f150515ec2bd12bc45250b");
var service = factory.CreateChannel();
var result = service.Test();
Console.WriteLine(result);
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string Test();
}
请注意,有多种使用证书的方法。此处,客户端和服务器端均受证书保护,服务器端使用证书对客户端进行身份验证,客户端在调用服务时应提供客户端证书。https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/message-security-with-a-certificate-clienthttps://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/transport-security-with-certificate-authentication请随时告诉我是否有什么我可以帮助的。