打开流式订阅时的EWS ServiceRequestException

时间:2018-06-13 18:44:31

标签: c# exchangewebservices

我正在尝试将连接流式传输到我公司的Exchange服务器以监控邮箱。我按照EWS文档创建然后打开StreamingSubscriptionConnection。在调用Open方法之后,我的应用程序会旋转,直到它抛出ServiceRequestException和timesout。我是否错误地配置了什么?我似乎无法将其连接起来。

代码:

static StreamingSubscriptionConnection connection;
static void Main(string[] args)
{
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
    {
        UseDefaultCredentials = true,
        Url = new Uri("https://webmail.company.com/ews/exchange.asmx")
    };

    SetStreamingNotifications(service);

    Console.ReadKey();
}

public static void SetStreamingNotifications(ExchangeService service)
{
    StreamingSubscription subscription;
    service.HttpHeaders.Add("X-AnchorMailbox", "email@company.com");
    service.HttpHeaders.Add("X-PreferServerAffinity", "true");

    // Subscribe to streaming notifications in the Inbox. 
    subscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox },
            EventType.NewMail,
            EventType.Modified,
            EventType.Deleted,
            EventType.Created,
            EventType.Moved,
            EventType.Copied);

    // Create a streaming connection to the service object, over which events are returned to the client.
    // Keep the streaming connection open for 30 minutes.
    connection = new StreamingSubscriptionConnection(subscription.Service, 30);
    connection.AddSubscription(subscription);
    connection.OnNotificationEvent += OnNotificationEvent;
    connection.OnSubscriptionError += SubscriptionError;
    connection.OnDisconnect += OnDisconnect;
    try
    {
        //Never get past this block, only throws ServiceRequestException
        connection.Open();
    }
    catch (ServiceRequestException e)
    {
        service.Timeout = 200000;
        try
        {
            DateTime dt = DateTime.Now;
            connection.Open();
            Console.WriteLine("Opening the connection took longer than expected: " + (int)Math.Round((DateTime.Now - dt).TotalSeconds) + "s");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Opening the connection failed twice: " + ex.Message + " after " + e.Message);
        }
        finally
        {
            service.Timeout = 100000;
        }
    }
    catch (Exception e)
    {
       Console.WriteLine("Opening the connection failed: " + e.Message);
    }

    Console.WriteLine($"Connection Open:{connection.IsOpen}");
}

我使用的EWS版本是V2.2.0,但我也尝试过与Microsoft.Exchange.WebServices.NETStandard v1.1.2相同的代码。

1 个答案:

答案 0 :(得分:0)

测试流式订阅的简便方法是使用EWSeditor https://github.com/dseph/EwsEditor/releases中的测试功能。

您发布的代码看起来不错,但您没有为订阅指定任何凭据或要连接的邮箱。因此,它将尝试连接到当前凭据的任何内容,如果该用户具有邮箱等可能失败的地方。但是如果你可以在EWSEditor中使用它,那么你可以比较ewseditor中发生的事情以及使用类似fiddler来查看请求等代码所发生的事情。