如何在 dot net core 2.1 项目中增加 WCF 服务的超时值

Rya*_*son 4 wcf .net-core asp.net-core visual-studio-2017

我发布此消息是因为我无法在 Stack Overflow 上找到任何通过连接服务添加服务引用来解决使用 WCF 的 .Net-Core 项目的问题的地方。

我的问题是由于长时间运行的操作请求,我面临客户端超时。

那么,如何增加 wcf 客户端对象的超时值,因为 .Net-Core 不再使用 web 配置来存储 WCF 服务引用的配置值?(请参阅我提供的答案)

小智 12

Ryan Wilson 的回答将有效,但前提是您尝试更新服务。Reference.cs 将被覆盖。在 .NET Core 3.1 中,您可以通过语法修改绑定超时:

 public MemoqTMServiceClass(string api_key)
    {
        
        client = new TMServiceClient();
        
        var eab = new EndpointAddressBuilder(client.Endpoint.Address);

        eab.Headers.Add(
              AddressHeader.CreateAddressHeader("ApiKey",  // Header Name
                                                 string.Empty,           // Namespace
                                                 api_key));  // Header Value

        client.Endpoint.Address = eab.ToEndpointAddress();
        client.Endpoint.Binding.CloseTimeout = new TimeSpan(2, 0, 0);
        client.Endpoint.Binding.OpenTimeout = new TimeSpan(2, 0, 0);
        client.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
        client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 10, 0);
    }
Run Code Online (Sandbox Code Playgroud)


Rya*_*son 8

在解决方案资源管理器中的连接服务下,添加 WCF 服务后,会为该服务生成一些文件。您应该会看到一个文件夹,其名称是您为 WCF 服务引用提供的名称,在该文件夹下有一个Getting Started,ConnectedService.json和一个Reference.cs文件。

要增加任何客户端服务对象的超时值,请打开Reference.cs和定位方法:GetBindingForEndpoint

在此方法中,您应该看到如下内容:

if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IYourService))
            {
                System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
                result.MaxBufferSize = int.MaxValue;
                result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
                result.MaxReceivedMessageSize = int.MaxValue;
                result.AllowCookies = true;
                //Here's where you can set the timeout values
                result.SendTimeout = new System.TimeSpan(0, 5, 0);
                result.ReceiveTimeout = new System.TimeSpan(0, 5, 0);

                return result;
            }
Run Code Online (Sandbox Code Playgroud)

只需使用result.您想要增加的超时,例如SendTimeoutReceiveTimeout等,并将其设置为具有所需超时值的新 TimeSpan。

我希望这被证明是对某人有用的帖子。


小智 5

只需在生成的代理类中实现以下部分方法即可配置服务端点。将部分方法放在您自己的文件中,以确保它不会被覆盖。

static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials);
Run Code Online (Sandbox Code Playgroud)