C#WCF Web Api 4 MaxReceivedMessageSize

我正在使用WCF Web Api 4.0框架并且运行到maxReceivedMessageSize已超过65,000错误。

我已经更新了我的webconfig看起来像这样但是因为我使用了WCF Web Api我认为这已不再使用了,因为我不再使用webHttpEndpoint了?

  <!-- Configure the WCF REST service base address via the global.asax.cs file and the default endpoint via the attributes on the  element below -->   

在新的WCF Web Api中,我在哪里指定MaxReceivedMessageSize?

我也尝试过CustomHttpOperationHandlerFactory无济于事:

  public class CustomHttpOperationHandlerFactory: HttpOperationHandlerFactory { protected override System.Collections.ObjectModel.Collection OnCreateRequestHandlers(System.ServiceModel.Description.ServiceEndpoint endpoint, HttpOperationDescription operation) { var binding = (HttpBinding)endpoint.Binding; binding.MaxReceivedMessageSize = Int32.MaxValue; return base.OnCreateRequestHandlers(endpoint, operation); } } 

如果您尝试以编程方式执行此操作(通过使用MapServiceRoute和HttpHostConfiguration.Create),则执行此操作的方式如下:

 IHttpHostConfigurationBuilder httpHostConfiguration = HttpHostConfiguration.Create(); //And add on whatever configuration details you would normally have RouteTable.Routes.MapServiceRoute(serviceUri, httpHostConfiguration); 

NoMessageSizeLimitHostConfig是HttpConfigurableServiceHostFactory的扩展,类似于:

 public class NoMessageSizeLimitHostConfig : HttpConfigurableServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { var host = base.CreateServiceHost(serviceType, baseAddresses); foreach (var endpoint in host.Description.Endpoints) { var binding = endpoint.Binding as HttpBinding; if (binding != null) { binding.MaxReceivedMessageSize = Int32.MaxValue; binding.MaxBufferPoolSize = Int32.MaxValue; binding.MaxBufferSize = Int32.MaxValue; binding.TransferMode = TransferMode.Streamed; } } return host; } } 

maxReceivedMessageSize是您必须在您使用的绑定上定义的属性。 .Net 4中的WCF引入了简化配置,因此如果您不配置任何内容,将使用默认值。 下面的示例对wshttpBinding有效,您可以根据您使用的绑定对其进行修改,并在service.odeml绑定部分中将其注册到您的web.config中(假设您使用的是IIS托管服务)。

         

HTH Dominik

如果您在IIS中托管,则可以在定义路由的位置设置值(在我的示例中为global.asax)。 如果将TransferMode设置为buffered(默认值),则还需要将MaxBufferSize设置为与MaxReceivedMessageSize相同的值。

 protected void Application_Start() { var config = new HttpConfiguration(); config.MaxReceivedMessageSize = int.MaxValue; config.MaxBufferSize = int.MaxValue; RouteTable.Routes.MapServiceRoute("api", config); } 

这是你在代码中做到这一点的方法

 var endpoint = ((HttpEndpoint)host.Description.Endpoints[0]); //Assuming one endpoint endpoint.TransferMode = TransferMode.Streamed; endpoint.MaxReceivedMessageSize = 1024 * 1024 * 10; // Allow files up to 10MB 

如果您创建自己的自定义主机(从标准主机派生),则可以重载以配置HttpEndpoint的方法。