In the previous post “Getting started with Dapr for .NET Developers“ we have seen how easy it was to expose a web API written in .NET and the power of exposing it through Dapr sidecar. In this post, we are looking at the different possible ways to invoke that service.
Introduction
Dapr through its Service Invocation building block makes it easy to have your application reliably and securely communicate with other applications using the standard HTTP protocols.
It is possible to invoke service by just leveraging the HTTP protocol and a simple .NET HttpClient.
Calling Dapr sidecar with .NET HttpClient
Calling Dapr sidecar with .NET HttpClient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Json; using WeatherForecastServiceGrpcClient;
var client = new HttpClient();
var weatherForecasts = await client.GetFromJsonAsync<List<WeatherForecast>>( "http://localhost:3500/v1.0/invoke/weatherforecastservice/method/weatherforecast");
This has the advantage that your code depends only on .NET, no third-party dependencies. The drawback is that you don’t get any help to build the URI to call the service.
We get exactly the same output result but this time we just had to craft an easy URI “http://weatherforecastservice/weatherforecast“ composed only of the Dapr app-id and the method-name of our service.
Calling Dapr sidecar with DaprClient
Calling Dapr sidecar with Dapr .NET SDK
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
using System; using System.Collections.Generic; using System.Net.Http; using Dapr.Client; using WeatherForecastServiceGrpcClient;
usingvar client = new DaprClientBuilder().Build();
var weatherForecasts = await client.InvokeMethodAsync<List<WeatherForecast>>( HttpMethod.Get, "weatherforecastservice", "weatherforecast"); foreach (var weatherForecast in weatherForecasts) { Console.WriteLine( $"Date:{weatherForecast.Date}, TemperatureC:{weatherForecast.TemperatureC}, Summary:{weatherForecast.Summary}"); }
Using the DaprClient we only had to specify the HTTP method, the Dapr app-id and the method-name of our service.
Conclusion
We have seen the different ways developers can use .NET with and without Dapr .NET SDK to call a service exposed through a Dapr sidecar. For some more in-depth reading about that topic, I recommend you to read “The Dapr service invocation building block” from the Dapr for .NET Developers book.
I am an experienced Team Leader & Distinguished Solution Architect with a passion for shipping high-quality products by empowering development team and culture toward an agile mindset. I bring technical vision and strategy, leading engineering teams to move product, processes and architecture forward.