Microservices with .NET Core Web API, EntityFrameworkCore and Ocelot API Gateway

Hi Guys,

I created a simple Microservices solution using .NET Core Web API, EntityFrameworkCore and Ocelot API Gateway. Hope you like it.

1) Solution 

The solution consists of four .NET Core Projects. APIGateway, ProductMicroservice, UserMicroservice are Web API projects while Microsoft.DataAccess is a class library with EntityFrameworkCore. And this project is referred by ProductMicroservice, UserMicroservice.





















2) UserMicroservice 

This project has a simple UserController as following,

namespace UserMicroservice.Controllers
{
    [Route("api/[controller]")]
    public class UserController : Controller
    {
        DatabaseContext _databaseContext;
        public UserController()
        {
            _databaseContext = new DatabaseContext();
        }
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<User> Get()
        {
            return _databaseContext.Users.ToList();
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public User Get(int id)
        {
            return _databaseContext.Users.Find(id);
        }

        // POST api/<controller>
        [HttpPost]
        public IActionResult Post([FromBody]User model)
        {
            try
            {
                _databaseContext.Users.Add(model);
                _databaseContext.SaveChanges();
                return StatusCode(StatusCodes.Status201Created, model);
            }
            catch (Exception)
            {

                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

        
    }
}

3) ProductMicroservice

This project has a simple ProductController as following,

namespace ProductMicroservice.Controllers
{
    [Route("api/[controller]")]
    public class ProductController : Controller
    {
        DatabaseContext _databaseContext;
        public ProductController()
        {
            _databaseContext = new DatabaseContext();
        }
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<Product> Get()
        {
            return _databaseContext.Products.ToList();
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public Product Get(int id)
        {
            return _databaseContext.Products.Find(id);
        }

        // POST api/<controller>
        [HttpPost]
        public IActionResult Post([FromBody]Product model)
        {
            try
            {
                _databaseContext.Products.Add(model);
                _databaseContext.SaveChanges();
                return StatusCode(StatusCodes.Status201Created, model);
            }
            catch (Exception)
            {

                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }
    }
}

4) API Gateway

This Web API acts as the interface between end users and our microservices. This uses Ocelot, an opensource API Gateway with a ton of exciting features.

Please refer https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html 

- Startup.cs

namespace APIGateway
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
             services.AddOcelot();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

          
            await app.UseOcelot();
        }
    }
}

- Program.cs

namespace APIGateway
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            .ConfigureAppConfiguration((hostingConfig, config)=> {
                config.AddJsonFile("ocelot.json");
            });
    }
}

- ocelot.json

{


  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/user",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 53656
        }

      ],
      "UpstreamPathTemplate": "/user",
      "UpstreamHttpMethod": [ "GET", "POST" ]
    },
    {
      "DownstreamPathTemplate": "/api/user/{id}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 53656
        }

      ],
      "UpstreamPathTemplate": "/user/{id}",
      "UpstreamHttpMethod": [ "GET" ]
    },
    {
      "DownstreamPathTemplate": "/api/product",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 59090
        }

      ],
      "UpstreamPathTemplate": "/product",
      "UpstreamHttpMethod": [ "GET", "POST" ]
    },
    {
      "DownstreamPathTemplate": "/api/product/{id}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 59090
        }

      ],
      "UpstreamPathTemplate": "/product/{id}",
      "UpstreamHttpMethod": [ "GET" ]
    }

  ]
}

5) Running and testing API Gateway

- Right click on Solution -> Properties then Select "Multiple Startup Projects"
















- Run the solution by pressing F5 or pressing debug

- Call API Gateway using Postman





Comments