DEV Community

siddharth
siddharth

Posted on

Creating microservices in .Net core using ocelot apigateway

This is the second part where we are going to build the microservices. So, we will have an ocelot apigateway and two microservices are Products and Orders. Let's start with the microservices.

First create a new project from CLI. dotnet new webapi -n Products is the command to create a new web api project.

dotnet new webapi -o Products

Products

This is our first microservice called products. Now create new controller named ProductsController.cs.

using Microsoft.AspNetCore.Mvc;

namespace apigateway.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public List<string> Get()
    {
        List<string> products = new List<string>();
        products.Add("Samsung products");
        products.Add("Apple products");
        products.Add("Google products");
        products.Add("Microsoft products");
        return products;
    }
}
Enter fullscreen mode Exit fullscreen mode

This get method will return the list of products.Products microservice is running on a http://localhost:8001. When you hit the http://localhost:8001/api/products. It will return the following response.

Product response

Now we have one microservice up and running. Create second microservice called Orders. For creating the second microservice follow the same steps.

dotnet new webapi -o Orders

Orders

This is our second microservice called orders. Now create new controller named OrdersController.cs.

using Microsoft.AspNetCore.Mvc;

namespace apigateway.Controllers;

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public List<string> Get()
    {
        List<string> orders = new List<string>();
        orders.Add("Order 1");
        orders.Add("Order 2");
        orders.Add("Order 3");
        orders.Add("Order 4");
        return orders;
    }
}
Enter fullscreen mode Exit fullscreen mode

Orders microservice is running on a http://localhost:8002. When you hit http://localhost:8002/api/orders. It will return the following response.

Order response

This microservices are just for the implementing microservices architecture. Using this microservices you will get knowledge
of microservices architecture with an apigateway.

Now here is the main step. We have to implement an apigateway. Follow the same steps for creating project. We need to create one more project for an apigateway.

dotnet new webapi -o Apigateway

After creating project you have to install nuget package Ocelot. Now install that package.

Ocelot

After installing the package. We have to update program.cs .

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath).AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true).AddEnvironmentVariables();
builder.Services.AddOcelot(builder.Configuration);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
await app.UseOcelot();
app.Run();
Enter fullscreen mode Exit fullscreen mode

Here we added some lines of code for ocelot. builder.Configuration.SetBasePath will sets the FileProvider for file-based providers to a PhysicalFileProvider with the base path. For that we have to create Ocelot.json.

Ocelot.json

{
    "Routes": [
        {
            "DownstreamPathTemplate": "/api/products",
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts": [
                {
                    "Host": "localhost",
                    "Port": 8001
                }
            ],
            "UpstreamPathTemplate": "/products",
            "UpstreamHttpMethod": [
                "Get"
            ]
        },
        {
            "DownstreamPathTemplate": "/api/orders",
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts": [
                {
                    "Host": "localhost",
                    "Port": 8002
                }
            ],
            "UpstreamPathTemplate": "/orders",
            "UpstreamHttpMethod": [
                "Get"
            ]
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

DownstreamPathTemplate : The endpoint of a microservice.
DownstreamScheme : The scheme of a microservice.
DownstreamHostAndPorts : Here you need to define the host and port of the microservice.
UpstreamPathTemplate : The path at which the client will request the Ocelot Apigateway.
UpstreamHttpMethod : The Http method to the apigateway. The method should match with the endpoint method.

Apigateway is running on a http://localhost:8888. Apigateway will act as a single entry point for our all microservices. Lets test whether an apigateway working right or not.

postman response for products

postman response for orders

In next article we are going to dockerize the microservices and apigateway.

Oldest comments (3)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

Hello. Good introduction on Ocelot. I actually have an issue with Ocelot's way of configuring routes so I am making a nuget to resolve this. All is explained here.

I will appreciate very much the feedback that you, as an Ocelot user, can provide around the most popular properties you usually set.

Cheers!

Collapse
 
siddharth151199 profile image
siddharth

Hi @webjose
I will definitely try this nuget package.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Great! But not a nuget package just yet. I am working on providing support for List properties and Dictionary<string, string> properties. Once I have done that, I'll release the first version of the nuget. Stay tuned!