(纯代码)快速创建wcf rest 服务

因为有一个小工具需要和其它的业务对接数据,所以就试一下看能不能弄一个无需配置快速对接的方法出来,百(以)度(讹)过(传)后(讹),最后还是对照wcf配置对象调试出来了:

1.创建WebHttpBinding

2.添加ServiceMetadataBehavior

3.获取一个serverendpoint

4.指定WebHttpBehavior格式

         /// <summary>
/// 快速创建一个WCF http服务
/// </summary>
/// <param name="contractType"></param>
/// <param name="serviceType"></param>
/// <param name="url"></param>
/// <param name="timeout"></param>
/// <param name="bufferSize"></param>
/// <param name="isDebug"></param>
/// <returns></returns>
public static ServiceHost CreateWebService(Type contractType, Type serviceType, string url, TimeSpan timeout, long bufferSize = , bool isDebug = true)
{
Uri baseAddress = new Uri(url); var serviceHost = new ServiceHost(serviceType, baseAddress); //1.创建WebHttpBinding
var binding = new WebHttpBinding(WebHttpSecurityMode.None); binding.Security = new WebHttpSecurity() { Mode = WebHttpSecurityMode.None, Transport = null }; binding.MaxBufferPoolSize = binding.MaxReceivedMessageSize = bufferSize; binding.OpenTimeout = binding.CloseTimeout = binding.SendTimeout = binding.ReceiveTimeout = timeout; binding.UseDefaultWebProxy = false; binding.ProxyAddress = null; var readerQuotas = new System.Xml.XmlDictionaryReaderQuotas(); readerQuotas.MaxArrayLength = readerQuotas.MaxBytesPerRead = readerQuotas.MaxDepth =
readerQuotas.MaxNameTableCharCount = readerQuotas.MaxStringContentLength = (int)bufferSize; binding.ReaderQuotas = readerQuotas; //2.添加ServiceMetadataBehavior
if (serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; //behavior.HttpsGetEnabled = false; serviceHost.Description.Behaviors.Add(behavior);
} if (serviceHost.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null)
{
ServiceThrottlingBehavior behavior = new ServiceThrottlingBehavior(); behavior.MaxConcurrentCalls = behavior.MaxConcurrentInstances = behavior.MaxConcurrentSessions = (int)bufferSize; serviceHost.Description.Behaviors.Add(behavior);
}
//3.获取一个serverendpoint
var serviceEndpoint = serviceHost.AddServiceEndpoint(contractType, binding, baseAddress); //4.指定WebHttpBehavior格式
//需引用System.ServiceModel.Web.dll
WebHttpBehavior webHttpBehavior = new WebHttpBehavior()
{
AutomaticFormatSelectionEnabled = false,
DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare,
DefaultOutgoingResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json,
DefaultOutgoingRequestFormat = System.ServiceModel.Web.WebMessageFormat.Json,
FaultExceptionEnabled = isDebug,
HelpEnabled = isDebug
}; serviceEndpoint.Behaviors.Add(webHttpBehavior); serviceHost.Opened += delegate
{
Console.WriteLine("{0}已启动!", serviceType.Name);
}; return serviceHost;
}

发布一个wcf  rest 服务只需要

  WCFServiceFactory.CreateWebService(typeof(ITestContract),typeof(TestService),"http://127.0.0.1:39654/",new TimeSpan(, , ),true).Open();
上一篇:自用游戏HTML5 sdk技术设计手册


下一篇:PHP求职备考