我有一个用代码创建的自托管 Web 服务:
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();
}
}
这工作正常,但是当我尝试发送大块数据时,我得到以下异常:
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, "");
...