透過 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());