.Net Core Kestrel Web Server Uygulaması

Merhaba, önceki blog yazımda .net core için web server yapılarından bahsetmiştim. Kestrel web server ile console uygulamasını self host olarak kullanabileceğimiz örnek bir uygulamayı paylaşmaya çalışacağım.
Visual Studio 2017 ‘de .Net Core kısmından Console App (.Net Core) seçerek yeni bir solution oluşturuyoruz. Proje Dependencies kısmından Nuget package manager kullanarak Microsoft.AspNetCore.Server.Kestrel kütüphanesini projemize ekleyerek Kestrel web server console uygulumamıza eklemiş oluyoruz.
Uygulamanın ve servislerin configuration sağlamak için projemize Startup isminde bir sınıf ekliyoruz. Startup sınıfımız ;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace KestrelConsoleApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Dependencies here !!!

//services.AddDataProtection();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async (context) =>
{
//Server Response Here !!!

context.Response.ContentType = "text/html";
await context.Response
.WriteAsync("<p>Hosted by Kestrel</p>" + context.Request.Query.ToString() + context.Request.Headers.ToString());

});

}
}
}

Uygulamamıza gelen isteklere Configure methodunda context.Response kullanarak sonuç değerleri verebiliriz. Hosting configuration ile browserdan yada diğer bir uygulamadan alabiliriz. Bunun için uygulamamızda bulunan Program sınıfının içersinde WebHostBuilder ile kestrel configuration’ı aşağıdaki şekilde yapmamız gerekmektedir.

using Microsoft.AspNetCore.Hosting;
using System;

namespace KestrelConsoleApp
{
class Program
{
static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.AllowSynchronousIO = true;
options.AddServerHeader = true;

})
.Build();
host.Run();
}
}
}
Uygulamamızı çalıştırdığımızda;
Kestrel web server çalışacak ve varsayılan olarak http://localhost:5000 adresini dinlemeye başayacaktır.Bu adrese browser ile bağlandığımızda sunucuya istek gönderilecek ve Configure methodunda yazdığımız response değerlerini görüntüleyeceğiz.
Basit örnek uygulamamızın kodlarını https://github.com/muratguven/KestrelConsoleApp adresinden erişebilirsiniz.
guvenmur avatarı