Client

Note

If you haven’t already, try out one of the quickstarts for a quick walk-through on how to use the Dapr .NET SDK with an API building block.

The .NET SDK allows you to interface with all of the Dapr building blocks.

  1. var client = DaprClient.CreateInvokeHttpClient(appId: "routing");
  2. var deposit = new Transaction { Id = "17", Amount = 99m };
  3. var response = await client.PostAsJsonAsync("/deposit", deposit, cancellationToken);
  4. var account = await response.Content.ReadFromJsonAsync<Account>(cancellationToken: cancellationToken);
  5. Console.WriteLine("Returned: id:{0} | Balance:{1}", account.Id, account.Balance);

Save & get application state

  1. var client = new DaprClientBuilder().Build();
  2. var state = new Widget() { Size = "small", Color = "yellow", };
  3. await client.SaveStateAsync(storeName, stateKeyName, state, cancellationToken: cancellationToken);
  4. Console.WriteLine("Saved State!");
  5. state = await client.GetStateAsync<Widget>(storeName, stateKeyName, cancellationToken: cancellationToken);
  6. Console.WriteLine($"Got State: {state.Size} {state.Color}");
  7. await client.DeleteStateAsync(storeName, stateKeyName, cancellationToken: cancellationToken);
  8. Console.WriteLine("Deleted State!");

Query State (Alpha)

  1. var query = "{" +
  2. "\"filter\": {" +
  3. "\"EQ\": { \"value.Id\": \"1\" }" +
  4. "}," +
  5. "\"sort\": [" +
  6. "{" +
  7. "\"key\": \"value.Balance\"," +
  8. "}" +
  9. "]" +
  10. "}";
  11. var client = new DaprClientBuilder().Build();
  12. var queryResponse = await client.QueryStateAsync<Account>("querystore", query, cancellationToken: cancellationToken);
  13. Console.WriteLine($"Got {queryResponse.Results.Count}");
  14. foreach (var account in queryResponse.Results)
  15. {
  16. Console.WriteLine($"Account: {account.Data.Id} has {account.Data.Balance}");
  • For a full list of state operations visit .
  1. var client = new DaprClientBuilder().Build();
  2. var eventData = new { Id = "17", Amount = 10m, };
  3. await client.PublishEventAsync(pubsubName, "deposit", eventData, cancellationToken);
  4. Console.WriteLine("Published deposit event!");
  • For a full list of state operations visit .
  • Visit .NET SDK examples for code samples and instructions to try out pub/sub

Interact with output bindings

Retrieve secrets

  1. var client = new DaprClientBuilder().Build();
  2. // Retrieve a key-value-pair-based secret - returns a Dictionary<string, string>
  3. var secrets = await client.GetSecretAsync("mysecretstore", "key-value-pair-secret");
  4. Console.WriteLine($"Got secret keys: {string.Join(", ", secrets.Keys)}");
  1. var client = new DaprClientBuilder().Build();
  2. // Retrieve a key-value-pair-based secret - returns a Dictionary<string, string>
  3. var secrets = await client.GetSecretAsync("mysecretstore", "key-value-pair-secret");
  4. Console.WriteLine($"Got secret keys: {string.Join(", ", secrets.Keys)}");
  5. // Retrieve a single-valued secret - returns a Dictionary<string, string>
  6. // containing a single value with the secret name as the key
  7. var data = await client.GetSecretAsync("mysecretstore", "single-value-secret");
  8. var value = data["single-value-secret"]
  9. Console.WriteLine("Got a secret value, I'm not going to be print it, it's a secret!");
  1. var client = new DaprClientBuilder().Build();
  2. // Retrieve a specific set of keys.
  3. var specificItems = await client.GetConfiguration("configstore", new List<string>() { "key1", "key2" });
  4. Console.WriteLine($"Here are my values:\n{specificItems[0].Key} -> {specificItems[0].Value}\n{specificItems[1].Key} -> {specificItems[1].Value}");
  5. // Retrieve all configuration items by providing an empty list.
  6. var specificItems = await client.GetConfiguration("configstore", new List<string>());
  7. Console.WriteLine($"I got {configItems.Count} entires!");
  8. foreach (var item in configItems)
  9. {
  10. Console.WriteLine($"{item.Key} -> {item.Value}")
  11. }

Subscribe to Configuration Keys (Alpha)

  1. var client = new DaprClientBuilder().Build();
  2. // The Subscribe Configuration API returns a wrapper around an IAsyncEnumerable<IEnumerable<ConfigurationItem>>.
  3. // or if the cancellation token is cancelled.
  4. var subscribeConfigurationResponse = await daprClient.SubscribeConfiguration(store, keys, metadata, cts.Token);
  5. await foreach (var items in subscribeConfigurationResponse.Source.WithCancellation(cts.Token))
  6. {
  7. foreach (var item in items)
  8. {
  9. Console.WriteLine($"{item.Key} -> {item.Value}")
  10. }
  11. }

Manage workflow instances (Alpha)

The .NET SDK provides a way to poll for the sidecar health, as well as a convenience method to wait for the sidecar to be ready.

Poll for health

This health endpoint returns true when both the sidecar and your application are up (fully initialized).

  1. var client = new DaprClientBuilder().Build();
  2. var isDaprReady = await client.CheckHealthAsync();
  3. if (isDaprReady)
  4. {
  5. // Execute Dapr dependent code.
  6. }

Poll for health (outbound)

This is best used when you want to utilize a Dapr component in your startup path, for instance, loading secrets from a secretstore.

  1. var client = new DaprClientBuilder().Build();
  2. var isDaprComponentsReady = await client.CheckOutboundHealthAsync();
  3. if (isDaprComponentsReady)
  4. {
  5. // Execute Dapr component dependent code.
  6. }

Wait for sidecar

The DaprClient also provides a helper method to wait for the sidecar to become healthy (components only). When using this method, it is recommended to include a CancellationToken to allow for the request to timeout. Below is an example of how this is used in the DaprSecretStoreConfigurationProvider.

  1. // Wait for the Dapr sidecar to report healthy before attempting use Dapr components.
  2. using (var tokenSource = new CancellationTokenSource(sidecarWaitTimeout))
  3. {
  4. await client.WaitForSidecarAsync(tokenSource.Token);
  5. }
  6. // Perform Dapr component operations here i.e. fetching secrets.

Shutdown the sidecar

  1. var client = new DaprClientBuilder().Build();
  2. await client.ShutdownSidecarAsync();