通过纯代码方式发布WCF服务
网络上搜索WCF服务,一般是寄宿在IIS,通过WebConfig方式配服务地址,接口类型等信息,但是对于我这样的懒人,目前项目在开发阶段,实在不愿意每次添加新服务就更新配置文件,于是使用了反射来加载服务接口,并用控制台程序发布服务,贴上代码如下。 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Configuration;
using Nebula.Proxy;
using System.Reflection;
using System.Configuration;
using System.Xml;
namespace MES_WCFService
{
public class HostIniter
{
public HostIniter()
{ }
private ServiceHostCollection hosts; private Type[] interfaceTypes;
private Type[] implTypes;
private string addressBase;
private string tcpPort;
private string httpPort;
private string basehttpPort;
/// <summary>
/// 通过反射获取所有服务接口及其实现类
/// </summary>
private void ScanService()
{
interfaceTypes = Assembly.Load(ConfigurationManager.AppSettings["interfaceDLLName"]).GetTypes();
implTypes = Assembly.Load(ConfigurationManager.AppSettings["implDLLName"]).GetTypes(); } public ServiceHostCollection InitHost()
{ hosts = new ServiceHostCollection();
addressBase = ConfigurationManager.AppSettings["baseAddress"];
tcpPort = ConfigurationManager.AppSettings["tcpPort"];
httpPort = ConfigurationManager.AppSettings["httpPort"];
basehttpPort = ConfigurationManager.AppSettings["basehttpPort"];
ScanService();
foreach (Type implType in implTypes)
{
try
{ if (!typeof(IWCFService).IsAssignableFrom(implType))
{
continue;
}
string baseNameSpace= "http://" + addressBase + ":" + httpPort + "/WCFService/";
string address = baseNameSpace + implType.Name;
Uri baseAddress = new Uri(address);
ServiceHost host = new ServiceHost(implType, baseAddress); //
Console.WriteLine("Add:" + implType.FullName);
Console.WriteLine("Address:" + address);
host.Description.Namespace = baseNameSpace;
host.Description.Name = implType.Name; ServiceSecurityAuditBehavior secBehacior = new ServiceSecurityAuditBehavior(); secBehacior.MessageAuthenticationAuditLevel = AuditLevel.None;
secBehacior.ServiceAuthorizationAuditLevel = AuditLevel.None; host.Description.Behaviors.Add(secBehacior); // secBehacior. ServiceMetadataBehavior metaBehavior = new ServiceMetadataBehavior();
metaBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
metaBehavior.HttpGetEnabled = true; ServiceDebugBehavior debugBehavior = host.Description.Behaviors[typeof(ServiceDebugBehavior)] as ServiceDebugBehavior;
debugBehavior.IncludeExceptionDetailInFaults = true; host.Description.Behaviors.Add(metaBehavior); Type t = host.GetType();
object obj = t.Assembly.CreateInstance("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior", true,
BindingFlags.CreateInstance | BindingFlags.Instance |
BindingFlags.NonPublic, null, new object[] { false, Int32.MaxValue },
null, null);
IServiceBehavior myServiceBehavior = obj as IServiceBehavior;
if (myServiceBehavior != null)
{
host.Description.Behaviors.Add(myServiceBehavior);
// Console.WriteLine("Add DataContractSerializerServiceBehavior !");
} ////host.Description.Behaviors.Add(debugBehavior);
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType == typeof(IWCFService))
{
continue;
} if (interfaceType.IsAssignableFrom(implType))
{
//本来是WSHttpBinding 为了让Java能调用到这些服务,遂改BasicHttpBinding BasicHttpBinding wsBinding = new BasicHttpBinding();
wsBinding.Security.Mode =BasicHttpSecurityMode.None;
wsBinding.MaxBufferPoolSize = ;
wsBinding.MaxReceivedMessageSize = int.MaxValue; wsBinding.ReaderQuotas.MaxStringContentLength = 0xfffffff;
wsBinding.ReaderQuotas.MaxArrayLength = 0xfffffff;
wsBinding.ReaderQuotas.MaxBytesPerRead = 0xfffffff;
wsBinding.ReaderQuotas.MaxDepth = 0xfffffff;
wsBinding.MessageEncoding = WSMessageEncoding.Text;
wsBinding.TextEncoding = Encoding.UTF8;
wsBinding.OpenTimeout = new TimeSpan(, , );
wsBinding.ReceiveTimeout = new TimeSpan(, , );
wsBinding.SendTimeout = new TimeSpan(, , ); ContractDescription contractDescription = ContractDescription.GetContract(interfaceType);
ServiceEndpoint httpEndpoint = new ServiceEndpoint(contractDescription, wsBinding, new EndpointAddress(baseAddress));
httpEndpoint.Name = "http" + implType.Name;
host.Description.Endpoints.Add(httpEndpoint); NetTcpBinding netTcpBinding = new NetTcpBinding() { Security = new NetTcpSecurity { Mode = SecurityMode.None } };
netTcpBinding.Security.Mode = SecurityMode.None;
netTcpBinding.MaxBufferPoolSize = ;
netTcpBinding.MaxReceivedMessageSize = int.MaxValue;
netTcpBinding.ReaderQuotas.MaxStringContentLength = 0xfffffff;
netTcpBinding.ReaderQuotas.MaxArrayLength = 0xfffffff;
netTcpBinding.ReaderQuotas.MaxBytesPerRead = 0xfffffff;
netTcpBinding.ReaderQuotas.MaxDepth = 0xfffffff;
netTcpBinding.OpenTimeout = new TimeSpan(, , );
netTcpBinding.ReceiveTimeout = new TimeSpan(, , );
netTcpBinding.SendTimeout = new TimeSpan(, , );
ServiceEndpoint tcpEndpoint = new ServiceEndpoint(contractDescription, netTcpBinding, new EndpointAddress("net.tcp://" + addressBase + ":" + tcpPort + "/WCFService/" + implType.Name));
tcpEndpoint.Name = "tcp" + implType.Name;
host.Description.Endpoints.Add(tcpEndpoint); host.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexHttpBinding(),
"mex"
); break;
}
}
//添加自定义的 Behavior
host.Description.Behaviors.Add(new MesServiceInterceptorAttribute()); hosts.Add(host);
} catch (Exception commProblem)
{ Console.WriteLine("There was a problem with this type ;"+implType.FullName);
Console.WriteLine("Message:" + commProblem.Message);
Console.WriteLine("StackTrace:" + commProblem.StackTrace);
Console.Read();
} }
return hosts;
} }
}
MesServiceInterceptorAttribute的代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels; namespace MES_WCFService
{
[AttributeUsage(AttributeTargets.Class)]
public class MesServiceInterceptorAttribute : Attribute, IServiceBehavior
{
protected MesOperationInterceptorAttribute CreateOperationInterceptor()
{
return new MesOperationInterceptorAttribute();
} public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase host)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
{
foreach (OperationDescription operation in endpoint.Contract.Operations)
{
bool checkresult = false;
foreach (IOperationBehavior behavior in operation.Behaviors)
{
if (behavior is MesOperationInterceptorAttribute)
{
checkresult = true;
break;
}
}
if (!checkresult)
{
operation.Behaviors.Add(CreateOperationInterceptor());
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{ } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{ }
}
}
MesOperationInterceptorAttribute的: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
namespace MES_WCFService
{
[AttributeUsage(AttributeTargets.Method)]
public class MesOperationInterceptorAttribute : Attribute, IOperationBehavior
{
//private InterceptionType m_InteType = InterceptionType.None;
private string _operatName;
public MesOperationInterceptorAttribute() { } //public MesOperationInterceptorAttribute(InterceptionType inteType)
//{
// this.m_InteType = inteType;
//} protected MesInvoker CreateInvoker(IOperationInvoker oldInvoker)
{
return new MesInvoker(oldInvoker, _operatName);
} public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{ } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{ } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
IOperationInvoker oldInvoker = dispatchOperation.Invoker;
_operatName = dispatchOperation.Name;
dispatchOperation.Invoker = CreateInvoker(oldInvoker);
} public void Validate(OperationDescription operationDescription)
{ }
}
}
通过纯代码方式发布WCF服务的更多相关文章
- 完全使用接口方式调用WCF 服务
客户端调用WCF服务可以通过添加服务引用的方式添加,这种方式使用起来比较简单,适合小项目使用.服务端与服务端的耦合较深,而且添加服务引用的方式生成一大堆臃肿的文件.本例探讨一种使用接口的方式使用WCF ...
- WCF入门教程(四)通过Host代码方式来承载服务
WCF入门教程(四)通过Host代码方式来承载服务 之前已经讲过WCF对外发布服务的具体方式. WCF入门教程(一)简介 Host承载,可以是web,也可以是控制台程序等等.比WebService有更 ...
- WCF入门教程(四)通过Host代码方式来承载服务 一个WCF使用TCP协议进行通协的例子 jquery ajax调用WCF,采用System.ServiceModel.WebHttpBinding System.ServiceModel.WSHttpBinding协议 学习WCF笔记之二 无废话WCF入门教程一[什么是WCF]
WCF入门教程(四)通过Host代码方式来承载服务 Posted on 2014-05-15 13:03 停留的风 阅读(7681) 评论(0) 编辑 收藏 WCF入门教程(四)通过Host代码方式来 ...
- WCF学习系列二_使用IIS发布WCF服务
原创作者:灰灰虫的家http://hi.baidu.com/grayworm 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS2008自带的WCFSVCHost(WCF服务主机)发 ...
- WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载]
原文:WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载] 我们有两种典型的WCF调用方式:通过SvcUtil.exe(或者添加Web引用)导入发布的服务元数据生成服务代理相关的代码 ...
- WCF开发实战系列二:使用IIS发布WCF服务
WCF开发实战系列二:使用IIS发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS200 ...
- WCF开发实战系列四:使用Windows服务发布WCF服务
WCF开发实战系列四:使用Windows服务发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇文章中我们通过编写的控制台程序或WinForm程序来为本 ...
- WCF 一步一步 发布 WCF服务 到 IIS (图)
WCF 一步一步 发布 WCF服务 到 IIS (图) 使用VS自带的WCFSVCHost(WCF服务主机)发布WCF服务,时刻开发人员测试使用. 下面我们来看一下如何在IIS中部发布一个WCF服务. ...
- WCF开发实战系列二:使用IIS发布WCF服务 转
转 http://www.cnblogs.com/poissonnotes/archive/2010/08/28/1811141.html 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们 ...
随机推荐
- Spring Cloud Dalston.SR5 BUG一记
使用Dalston.SR5版本的Zuul时, 发现Ribbon重试不能切换服务实例, 换成Edgware.SR3,同样的配置可以切换实例进行重试 还有个不升级所有Spring Cloud组件的方法,仅 ...
- 配置阿里云Docker镜像加速仓库
1.首先要有个阿里云的账号 2.访问:https://cr.console.aliyun.com 3.登陆后可看到: 我的加速地址:https://g65zw8cl.mirror.aliyuncs.c ...
- Cecos国内集成系统基于rhel6.5
整体上,secos对云.虚拟化.等整体的解决方案(一键打包),很不错.做出了有益的探索.... 本次测试基于版本测试,不得说官方文档也是挺全的,很好!!!! CecOS-1.4.2-Final-170 ...
- Fiddler配置https
问题描述: fiddler加载认证不成功... 问题解决: 手工生成认证证书 00.配置HTTPS 01.勾选https 02.添加ssh认证 11. 找到fiddler的安装目录 手工生成认证秘钥 ...
- java服务端微信小程序支付
发布时间:2018-10-05 技术:springboot+maven 概述 java微信小程序demo支付只需配置支付一下参数即可运行 详细 代码下载:http://www.demodash ...
- OpenCV 数字验证码识别
更新后代码下载链接在此! !! 点我下载 本文针对OpenCv入门人士.由于我也不是专门做图像的,仅仅是为了完毕一次模式识别的小作业. 主要完毕的功能就是自己主动识别图片中的数字.图片包含正常图片,有 ...
- 编译Boost库
VS版本: 虽然网络上有,但是还是记录下,找到VS的command prompt,然后切换到boost的根目录: 1.运行 bootstrap.bat 它在当前目录下会生成b2.exe2. 2.运行b ...
- 简单解决XP共享连接数10限制(转)
1.建立一个txt文件,在里面输入以下文字:net session /delete /y,并将其保存为clear session.bat文件.net session用于查看本机共享的会话详细情况,可以 ...
- 微信小程序-携带参数的二维码条形码生成
demo文件目录 index.js文件 //index.js var wxbarcode = require('../../utils/index.js'); Page({ data: { code: ...
- 【MySQL】乐观锁和悲观锁
最近学习了一下数据库的悲观锁和乐观锁,根据自己的理解和网上参考资料总结如下: 悲观锁介绍(百科): 悲观锁,正如其名,它指的是对数据被外界(包括本系统当前的其他事务,以及来自外部系统的事务处理)修改持 ...