Connect to Azure Web PubSub
Konten ini belum tersedia dalam bahasa Anda.
This page describes how consuming apps connect to an Azure Web PubSub resource that’s already modeled in your AppHost. For the AppHost API surface — adding a Web PubSub resource, hubs, event handlers, role assignments, and more — see Azure Web PubSub Hosting integration.
When you reference an Azure Web PubSub resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire Azure Web PubSub client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called web-pubsub becomes WEB_PUBSUB_URI.
The Azure Web PubSub resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Uri | The HTTPS service endpoint, with the format https://{resource-name}.webpubsub.azure.com |
Example:
WEB_PUBSUB_URI: https://webpubsub-abc123.webpubsub.azure.comConnection string formats
Section titled “Connection string formats”Azure Web PubSub clients accept two connection formats:
-
Service endpoint (recommended): Uses the endpoint URL with a managed identity / default credential. This is the format Aspire injects by default.
https://{account_name}.webpubsub.azure.com -
Full connection string (includes access key): Combines the
EndpointandAccessKeycomponents. Use this only when managed identity isn’t available.Endpoint=https://{account_name}.webpubsub.azure.com;AccessKey={account_key}
Connect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure Web PubSub resource named web-pubsub and references it from the consuming app.
For C# apps, the recommended approach is the Aspire Azure Web PubSub client integration. It registers a WebPubSubServiceClient through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Azure.Messaging.WebPubSub NuGet package in the client-consuming project:
dotnet add package Aspire.Azure.Messaging.WebPubSub#:package Aspire.Azure.Messaging.WebPubSub@*<PackageReference Include="Aspire.Azure.Messaging.WebPubSub" Version="*" />Add the Web PubSub service client
Section titled “Add the Web PubSub service client”In Program.cs, call AddAzureWebPubSubServiceClient on your IHostApplicationBuilder to register a WebPubSubServiceClient:
builder.AddAzureWebPubSubServiceClient( connectionName: "web-pubsub", settings => settings.HubName = "messages");Resolve the client through dependency injection:
public class ExampleService(WebPubSubServiceClient client){ // Use client...}Add keyed Web PubSub clients
Section titled “Add keyed Web PubSub clients”To register multiple WebPubSubServiceClient instances for different hubs, use AddKeyedAzureWebPubSubServiceClient:
builder.AddKeyedAzureWebPubSubServiceClient(name: "messages");builder.AddKeyedAzureWebPubSubServiceClient(name: "commands");Then resolve each client by key:
public class ExampleService( [FromKeyedServices("messages")] WebPubSubServiceClient messagesClient, [FromKeyedServices("commands")] WebPubSubServiceClient commandsClient){ // Use clients...}Configuration
Section titled “Configuration”The Aspire Azure Web PubSub client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddAzureWebPubSubServiceClient. Two formats are supported:
-
Service endpoint (recommended):
JSON — appsettings.json {"ConnectionStrings": {"web-pubsub": "https://{account_name}.webpubsub.azure.com"}} -
Full connection string with access key:
JSON — appsettings.json {"ConnectionStrings": {"web-pubsub": "Endpoint=https://{account_name}.webpubsub.azure.com;AccessKey={account_key}"}}
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads AzureMessagingWebPubSubSettings from appsettings.json using the Aspire:Azure:Messaging:WebPubSub key:
{ "Aspire": { "Azure": { "Messaging": { "WebPubSub": { "HubName": "messages", "DisableHealthChecks": false } } } }}Inline delegates. Pass an Action<AzureMessagingWebPubSubSettings> to configure settings inline:
builder.AddAzureWebPubSubServiceClient( "web-pubsub", settings => settings.DisableHealthChecks = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The Azure Web PubSub client integration registers a health check that verifies the service is reachable. The health check is wired into the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire Azure Web PubSub client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
AzureAzure.CoreAzure.IdentityAzure.Messaging.WebPubSub
Tracing activities:
Azure.Messaging.WebPubSub.*
Metrics: The Azure Web PubSub integration currently doesn’t support metrics by default due to limitations in the Azure SDK for .NET.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected endpoint URI from the environment and create a WebPubSubServiceClient directly:
using Azure.Messaging.WebPubSub;using Azure.Identity;
var endpoint = new Uri(Environment.GetEnvironmentVariable("WEB_PUBSUB_URI")!);var client = new WebPubSubServiceClient(endpoint, "messages", new DefaultAzureCredential());
// Use client...Install the Azure Web PubSub SDK for Go:
go get github.com/Azure/azure-sdk-for-go/sdk/messaging/webpubsubgo get github.com/Azure/azure-sdk-for-go/sdk/azidentityRead the injected environment variable and connect using managed identity:
package main
import ( "os" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/messaging/webpubsub")
func main() { // Read the Aspire-injected service endpoint endpoint := os.Getenv("WEB_PUBSUB_URI")
cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) }
client, err := webpubsub.NewClient(endpoint, cred, nil) if err != nil { panic(err) }
hubClient, err := client.NewHubClient("messages", nil) if err != nil { panic(err) }
_ = hubClient // Use hubClient to send messages...}Install the azure-messaging-webpubsubservice package:
pip install azure-messaging-webpubsubservice azure-identityRead the injected environment variable and connect using managed identity:
import osfrom azure.identity import DefaultAzureCredentialfrom azure.messaging.webpubsubservice import WebPubSubServiceClient
# Read the Aspire-injected service endpointendpoint = os.getenv("WEB_PUBSUB_URI")
client = WebPubSubServiceClient(endpoint=endpoint, hub="messages", credential=DefaultAzureCredential())
# Use client to send messages...Or use a full connection string with access key:
import osfrom azure.messaging.webpubsubservice import WebPubSubServiceClient
connection_string = os.getenv("AZURE_WEB_PUBSUB_CONNECTION_STRING")client = WebPubSubServiceClient.from_connection_string(connection_string, hub="messages")
# Use client...Install the @azure/web-pubsub package:
npm install @azure/web-pubsub @azure/identityRead the injected environment variable and connect using managed identity:
import { WebPubSubServiceClient } from '@azure/web-pubsub';import { DefaultAzureCredential } from '@azure/identity';
// Read the Aspire-injected service endpointconst endpoint = process.env.WEB_PUBSUB_URI!;
const client = new WebPubSubServiceClient( endpoint, new DefaultAzureCredential(), "messages" // hub name);
// Use client to send messages...Or use a full connection string with access key:
import { WebPubSubServiceClient } from '@azure/web-pubsub';
const connectionString = process.env.AZURE_WEB_PUBSUB_CONNECTION_STRING!;const client = new WebPubSubServiceClient(connectionString, "messages");
// Use client...