WCF - use without app.config

爷,独闯天下 提交于 2019-12-01 00:40:35

Sure - you can do all configuration in code.

Uri tcpBaseAddress = new Uri("net.tcp://localhost:8000/");

ServiceHost host = new ServiceHost(typeof(MyService),tcpBaseAddress);

Binding tcpBinding = new NetTcpBinding( );

//Use base address as address
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,"");
//Add relative address
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,"MyService");
//Ignore base address
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,
   "net.tcp://localhost:8001/MyService");

host.Open( );

http://en.csharp-online.net/WCF_Essentials%E2%80%94Programmatic_Endpoint_Configuration

Here is one that comes straight from our SharePoint code for our PDF Converter product. It uses HTTPBindings and completely bypasses config files.

    /// <summary>
    /// Configure the Bindings, endpoints and open the service using the specified address.
    /// </summary>
    /// <returns>An instance of the Web Service.</returns>
    public static DocumentConverterServiceClient OpenService(string address)
    {
        DocumentConverterServiceClient client = null;

        try
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            // ** Use standard Windows Security.
            binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            binding.Security.Transport.ClientCredentialType = 
                                                        HttpClientCredentialType.Windows;
            // ** Increase the Timeout to deal with (very) long running requests.
            binding.SendTimeout = TimeSpan.FromMinutes(30);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(30);
            // ** Set the maximum document size to 40MB
            binding.MaxReceivedMessageSize = 50*1024*1024;
            binding.ReaderQuotas.MaxArrayLength = 50 * 1024 * 1024;
            binding.ReaderQuotas.MaxStringContentLength = 50 * 1024 * 1024;

            // ** Specify an identity (any identity) in order to get it past .net3.5 sp1
            EndpointIdentity epi = EndpointIdentity.CreateUpnIdentity("unknown");
            EndpointAddress epa = new EndpointAddress(new Uri(address), epi);

            client = new DocumentConverterServiceClient(binding, epa);

            client.Open();

            return client;
        }
        catch (Exception)
        {
            CloseService(client);
            throw;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!