Wednesday 2 January 2019

What is AspNet Core Proxy and how to create it?

If we want to have a proxy on top of multiple micro-services based on specific route, we can use Microsoft.AspNetCore.Proxy Nuget Package it provide RunProxy as method extension under IApplicationBuilder, which allow us to configure mapping of micro-service.

Let's explore the diagram given below:


If we want to see 1-1 mapping for a simple actual implementation, we can see how easy it mapped in given below pic


So let's see how we need to manage the code in order for actual implementation.

Here is code snippet that we need to put in under ProxyApi, Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
 
namespace AppProxy
{
    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)
        {
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
 
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
 
            app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/Account/api"), builder => builder.RunProxy(new ProxyOptions {
                Scheme = "http",
                Host= "localhost",
                Port = "54169"
            }));
 
            app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/Order/api"), builder => builder.RunProxy(new ProxyOptions
            {
                Scheme = "http",
                Host = "localhost",
                Port = "54409"
            }));
        }
    }
}


Output could be easy understand by looking in to below pic:


Watch full Demo on YouTube
https://www.youtube.com/watch?v=4SqzXTpGcLY&t=141s