通过 Azure 中继混合连接发送请求
若要通过 Azure 中继发送和接收消息,则必须了解如何编写所需的代码。
假设你已在 Azure 中继中为信用检查服务创建了中继。 现在,你想要修改信用检查服务和调用该服务的客户端,使他们可以通过中继发送消息。 你需要了解如何编写此代码。
在此单元中,我们使用 HybridConnectionListener
和 HttpRequestMessage
等类来发送和响应消息。
使用 TokenProvider 传递凭据
侦听器和发送器组件在连接时必须向 Azure 中继标识自己。 对于任何混合连接,都可以使用 .NET TokenProvider
类传递此信息。 你在命名空间中创建共享访问策略时,Azure 创建了主密钥和辅助密钥。 此密钥是添加到 TokenProvider
以保护通信的凭据。
此代码演示如何配置凭据并将其添加到 TokenProvider
:
// Store credentials. In production code, keep these values in a secure location, such as Azure Key Vault.
private const string KeyName = "RootManageSharedAccessKey";
private const string Key = "<your key here>";
// Create and configure TokenProvider.
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
将侦听器连接到 Azure 中继
若要将侦听器连接到 Azure 中继服务,需要创建并配置 HybridConnectionListener
类的实例。 将中继的 URI 和 TokenProvider
传递给构造函数。
// Store the connection details.
private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
private const string ConnectionName = "{HybridConnectionName}";
// Create and configure the listener.
var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
接下来,订阅中继中的相关事件,例如连接事件。
listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
listener.Offline += (o, e) => { Console.WriteLine("Offline"); };
listener.Online += (o, e) => { Console.WriteLine("Online"); };
若要配置侦听器对消息的响应方式,请使用其 RequestHandler
属性。 若要发送响应,请使用 StreamWriter
。
listener.RequestHandler = (context) =>
{
// Configure the response status.
context.Response.StatusCode = HttpStatusCode.OK;
context.Response.StatusDescription = "OK";
// Use a stream writer to send text back.
using (var sw = new StreamWriter(context.Response.OutputStream))
{
sw.WriteLine("hello!");
}
// Remember to close the context.
context.Response.Close();
};
配置完侦听器后,将其打开以开始侦听消息。 因为中继、侦听器和发送器托管在不同的位置,因此可能需要一些时间来响应消息。 请务必为这些消息使用异步代码,以确保应用在等待响应时不会停止响应。 请注意以下代码中的异步 await
关键字和异步方法名称:
await listener.OpenAsync()
请记住在代码中的相应点关闭侦听器:
await listener.CloseAsync();
将发送器连接到 Azure 中继
对于发送器,没有特定于 Azure 中继的对象。 可以使用标准的 HttpRequestMessage
对象,就像调用任何 web 服务一样。
// Store the connection details.
private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
private const string ConnectionName = "{HybridConnectionName}";
// Formulate the URI.
var uri = new Uri(string.Format("https://{0}/{1}", RelayNamespace, ConnectionName));
// Create and configure the client. Use the Content property to specify the message text.
var client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = uri,
Method = HttpMethod.Get,
Content = new StringContent("Obtain credit check for Sara McMurray")
};
若要传递令牌,请将其添加到请求标头:
// Create the token from the token provider.
var token = (await tokenProvider.GetTokenAsync(uri.AbsoluteUri, TimeSpan.FromHours(1))).TokenString;
// Add the token to the headers.
request.Headers.Add("ServiceBusAuthorization", token);
现在,可以使用 SendAsync
方法发送消息,并异步获取响应:
// Send the request.
var response = await client.SendAsync(request);
// Display the result.
Console.WriteLine(await response.Content.ReadAsStringAsync());