When you are building a micro-service architecture then you have many internal services and a service implementing the API Gateway pattern acts as the one API surface for outsiders communicating with your application. The Gateway API needs to forward requests to your internal micro-services. To do this in Microsoft’s Service Fabric, you can use the Service Fabric Reverse Proxy or ServicePartitionResolver. Under the hood, Service Fabric Naming Service and other services are monitoring each instance and endpoint. Using the Reverse Proxy, you can communicate with other services without hard coding the endpoints. It is important not to hard code endpoints because when you start to scale the application you will want it to dynamically use different instances of the same service, like a load balancer.
This is an example of a ASP.NET Core Web API controller Post() method in the Gateway API that is resolving an endpoint using the ServicePartitionResolver to get an endpoint to call for the SampleOAuthService micro-service. Then it forwards the request and returns the response. In a production app, you can do more validation and rate limiting in the Gateway API Post() method.
public async Task<IActionResult> Post()
var resolver = ServicePartitionResolver.GetDefault();
var cancellationToken = new System.Threading.CancellationToken();
var p = await resolver.ResolveAsync(new Uri(“fabric:/SampleOAuthService/IdentityWebApi”), new ServicePartitionKey(), cancellationToken);
var body = reader.ReadToEnd();
var content = new StringContent(body, System.Text.Encoding.UTF8, “application/x-www-form-urlencoded”);
JObject addresses = JObject.Parse(p.GetEndpoint().Address);
string primaryReplicaAddress = (string)addresses[“Endpoints”].First();
var response = await http.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
JObject responseObject = JObject.Parse(responseContent);