【问题标题】:WCF sending the same exception even if the service endpoint address is valid即使服务端点地址有效,WCF 也会发送相同的异常
【发布时间】:2026-01-08 04:50:01
【问题描述】:

我在使用 WCF 时遇到了一个非常奇怪的问题。如果接收到无法访问的端点 IP 地址或服务无法绑定,我需要为 WCF 服务实施一些恢复行为。 如果应用程序在服务创建异常时失败,则流程很简单,它会终止它并向用户请求另一个 IP 地址并再次尝试创建服务。 (下面的代码sn-p)。如果地址无效,我会收到“在侦听 IP Endpoint=.121.10.11.11 时发生 TCP 错误(10049:请求的地址在其上下文中无效)”异常,但是如果我尝试第二次尝试有效地址 我有同样的例外,上次尝试的 IP 地址错误。这是一个代码:

ServiceHost service = null;
try
{
    Uri[] uris = { new Uri(Constants.PROTOCOL + "://" + address + ":" + port) };
    service = new ServiceHost(typeof(IRemoteService), uris);
    NetTcpBinding tcpBinding =
        WcfTcpRemoteServicesManager.LessLimitedNewNetTcpBinding(int.MaxValue,
            int.MaxValue, int.MaxValue);
    ServiceEndpoint ep = service.AddServiceEndpoint(implementedContract.FullName,
        tcpBinding, serviceName);
    var throttle =
        service.Description.Behaviors.Find<ServiceThrottlingBehavior>();
    if (throttle == null)
    {
        throttle = new ServiceThrottlingBehavior
        {
            MaxConcurrentCalls = Constants.MAX_CONCURRENT_CALLS,
            MaxConcurrentSessions = Constants.MAX_CONCURRENT_SESSIONS,
            MaxConcurrentInstances = Constants.MAX_CONCURRENT_INSTANCES
        };
        service.Description.Behaviors.Add(throttle);
    }
    service.Open();

}
catch (Exception e)
{
    _debugLog.WriteLineMessage(
        "Failed to open or create service exception. Exception message:" +
            e.Message);
    if (service!=null)
    {
        try
        {
            service.Close();
        }
        catch (Exception)
        {
            service.Abort();
            service.Close();
            throw e;
        }
    }
}

谢谢

【问题讨论】:

    标签: wcf service endpoint


    【解决方案1】:

    你捕捉到异常 e,然后你捕捉到另一个异常,但你抛出了原来的异常 e。

    不确定这是否是您的问题,但它可能会导致您返回一个令人困惑的异常。

    编辑

    现在我读得更仔细了。

    问题是上下文和地址不匹配。我看到代码使用了netTcpBinding:

    • 检查地址是否匹配,CONSTANTS.Protocol 的值是多少?
    • 检查配置文件没有冲突。

    【讨论】:

    • 这是意料之中的行为,我想更新上层这里抛出异常,但是优雅地关闭ServiceHost。
    • 但是只有在关闭服务主机产生异常的情况下才会抛出它。如果服务主机的关闭工作上层不会得到异常
    • 你是对的,同样的行也应该添加到上面的异常中,但不幸的是最初的问题仍未解决。
    • Hello Shiraz:CONSTANTS.Protocol 值为:public const string PROTOCOL = "net.tcp";配置文件中没有冲突。如果抛出异常,上下文如何保存先前的地址?如果我尝试将一个有效地址更改为另一个有效地址,则操作成功,只有在异常之后才会失败。是否可以在服务器端清除上下文?
    最近更新 更多