I have a self hosted web service that is created in code:
protected void StartService(Type serviceType, Type implementedContract, string serviceDescription)
{
Uri addressTcp = new Uri(_baseAddressTcp + serviceDescription);
ServiceHost selfHost = new ServiceHost(serviceType, addressTcp);
Globals.Tracer.GeneralTrace.TraceEvent(TraceEventType.Information, 0, "Starting service " + addressTcp.ToString());
try
{
selfHost.AddServiceEndpoint(implementedContract, new NetTcpBinding(SecurityMode.None), "");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
selfHost.Description.Behaviors.Add(smb);
System.ServiceModel.Channels.Binding binding = MetadataExchangeBindings.CreateMexTcpBinding();
selfHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, "mex");
selfHost.Open();
ServiceInfo si = new ServiceInfo(serviceType, implementedContract, selfHost, serviceDescription);
try
{
lock (_hostedServices)
{
_hostedServices.Add(serviceType, si);
}
}
catch (ArgumentException)
{
//...
}
}
catch (CommunicationException ce)
{
//...
selfHost.Abort();
}
}
This works ok, but when I try to send large chunks of data I get the following exception:
Error: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter @@@ . The InnerException message was 'There was an error deserializing the object of type @@@. The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader.'. Please see InnerException for more details. at: at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
The solution appears to be adding MaxStringContentLength property to the binding. I understand how to do it in the Web.config (link):
... binding name="wsHttpBindingSettings" maxReceivedMessageSize="2147483647">
I am looking for a way of modifying the binding's maxReceivedMessageSize in code. Is that even possible with the type of binding that I am using?
Thanks.
Edit: After learning some more (and with the guidance of the responses I received) I understand the problem: I was trying to modify the MEX part of the service, which is only used to advertise it, see link. I should have modified the binding of the NetTcpBinding (first line in the try statement). now my (working) code looks like this:
...
try
{
//add the service itself
NetTcpBinding servciceBinding = new NetTcpBinding(SecurityMode.None);
servciceBinding.ReaderQuotas.MaxStringContentLength = 256 * 1024;
servciceBinding.ReaderQuotas.MaxArrayLength = 256 * 1024;
servciceBinding.ReaderQuotas.MaxBytesPerRead = 256 * 1024;
selfHost.AddServiceEndpoint(implementedContract, servciceBinding, "");
...