从Windows服务访问Service Bus 1.1

时间:2015-04-19 16:12:07

标签: windows-services servicebus

我已经为Windows服务器设置了服务总线1.1,并尝试使用以下代码访问它。

    var sbUriList = new List<Uri>() { new UriBuilder { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri };
    var httpsUriList = new List<Uri>() { new UriBuilder { Scheme = "https", Host = ServerFQDN, Path = ServiceNamespace, Port = HttpPort }.Uri };

    NetworkCredential credential = new NetworkCredential("<User Name>", "<Password>", "<Domain>");

    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, cert, chain, ssl) => { return true; });

    TokenProvider tokenProvider = TokenProvider.CreateOAuthTokenProvider(httpsUriList, credential);
    messageFactory = MessagingFactory.Create(sbUriList, tokenProvider);



    ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
    connBuilder.ManagementPort = HttpPort;
    connBuilder.RuntimePort = TcpPort;
    connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri);
    connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNamespace }.Uri);

    namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

if (!namespaceManager.QueueExists(queuename))
{
    namespaceManager.CreateQueue(queuename);
}

如果我从控制台应用程序运行我的代码,这可以正常工作,但是如果我把它放在 Windows服务中并在本地服务或< strong>本地系统代码在尝试检查以下行namespaceManager.QueueExists(queuename)中是否存在队列时抛出以下异常。

Unexpected exception : System.UnauthorizedAccessException: The remote server returned an error: (401) Unauthorized. Manage claim is required for this operation..TrackingId:5be1365e-b4ae-4555-b81b-dcbef96be9d0_GIE11LT32PD622,TimeStamp:4/19/2015 3:51:28 PM ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.GetAsyncResult`1.<GetAsyncSteps>b__2d(GetAsyncResult`1 thisPtr, IAsyncResult r)
   at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult result)
   --- End of inner exception stack trace ---

有人可以帮我理解我做错了吗?

1 个答案:

答案 0 :(得分:3)

最后在我的代码中发现了这个问题,我想我会分享它,以防其他人有同样的问题。

我的问题是在命名空间中我没有设置令牌如下:

namespaceManager.Settings.TokenProvider = tokenProvider;

因此使用错误的令牌进行连接,从而导致错误。