Connect Aspire apps to Dapr sidecars
此内容尚不支持你的语言。
This page describes how an app connects to the Dapr sidecar attached to it. For sidecar and component configuration in the AppHost, see Set up Dapr resources in the AppHost.
Connection properties
Section titled “Connection properties”The hosting integration injects these environment variables into an app resource that has a Dapr sidecar:
| Environment variable | Description |
|---|---|
DAPR_HTTP_PORT | Port for the sidecar’s HTTP API |
DAPR_GRPC_PORT | Port for the sidecar’s gRPC API |
DAPR_HTTP_ENDPOINT | Full endpoint for the sidecar’s HTTP API |
DAPR_GRPC_ENDPOINT | Full endpoint for the sidecar’s gRPC API |
These variables are added in run mode. Pick the HTTP or gRPC endpoint that matches the SDK transport you configure.
Connect from your app
Section titled “Connect from your app”Each example uses the sidecar endpoint injected into the app resource.
Install the official 📦 Dapr.Client package:
dotnet add package Dapr.Client#:package Dapr.Client@*<PackageReference Include="Dapr.Client" Version="*" />using Dapr.Client;
var endpoint = Environment.GetEnvironmentVariable("DAPR_GRPC_ENDPOINT") ?? throw new InvalidOperationException("DAPR_GRPC_ENDPOINT is not set.");
using var daprClient = new DaprClientBuilder() .UseGrpcEndpoint(endpoint) .Build();
var product = await daprClient.GetStateAsync<string>( "statestore", "product-1");ASP.NET Core apps can instead install 📦 Dapr.AspNetCore and register DaprClient with dependency injection.
Install the official Dapr JavaScript SDK:
npm install @dapr/daprimport { CommunicationProtocolEnum, DaprClient, HttpMethod } from '@dapr/dapr';
const endpoint = new URL(process.env.DAPR_HTTP_ENDPOINT!);const client = new DaprClient({ daprHost: endpoint.hostname, daprPort: endpoint.port, communicationProtocol: CommunicationProtocolEnum.HTTP,});
const response = await client.invoker.invoke( 'catalog-api', 'api/data', HttpMethod.GET);Install the official Dapr Python SDK:
pip install daprimport osfrom urllib.parse import urlparse
from dapr.clients import DaprClient
endpoint = urlparse(os.environ["DAPR_GRPC_ENDPOINT"])
with DaprClient(address=endpoint.netloc) as client: response = client.invoke_method( app_id="catalog-api", method_name="api/data", http_verb="GET", ) print(response.text())Install the official Dapr Go SDK:
go get github.com/dapr/go-sdk/clientpackage main
import ( "context" "fmt" "net/url" "os"
dapr "github.com/dapr/go-sdk/client")
func main() { endpoint, err := url.Parse(os.Getenv("DAPR_GRPC_ENDPOINT")) if err != nil { panic(err) }
client, err := dapr.NewClientWithAddress(endpoint.Host) if err != nil { panic(err) } defer client.Close()
response, err := client.InvokeMethod( context.Background(), "catalog-api", "api/data", "get", ) if err != nil { panic(err) }
fmt.Println(string(response))}