DEV Community

MustafaSamedYeyin
MustafaSamedYeyin

Posted on

2

Asp.net core Routing Route Handler Giriş.

Diyelim ki controller'lara düşmeyen bir istek yapmanız gerekiyor mesela mustafa'ya bir şeyler söyleteceksiniz ama bunun için controller da metot koymak gereksiz diye düşünüyorsunuz.

Örneğin:

https://localhost:5001/mustafa?saysomething=BenimAdimMustafa
Enter fullscreen mode Exit fullscreen mode

dediğimizde sayfada :

BenimAdimMustafa
Enter fullscreen mode Exit fullscreen mode

yazmasını istiyoruz ama bu isteğin controller'dan geçmesini de istemiyoruz. O zaman ne yaparız ?

1.) Model-view-controller projesi oluşturun.

2.) SaySomething adında bir class oluşturalım :

public class SaySomething
    {
        public RequestDelegate Handler()
        {
            return async c => await Task.Run(async () =>
            {
                string message = c.Request.Query["saysomething"].ToString();
                await c.Response.WriteAsync(message);
            });
        }
    }
Enter fullscreen mode Exit fullscreen mode

3.) endpoint'lerimizi aşağıdaki gibi değiştirelim :

app.UseEndpoints(endpoints =>
            {
                endpoints.Map("mustafa", new SaySomething().Handler());
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
Enter fullscreen mode Exit fullscreen mode

Şimdi uygulamayı çalıştıralam ve aşağıdaki linke istek atalım :

https://localhost:5001/mustafa?saysomething=BenimAdimMustafa

Gördüğünüz üzere :

Image description

Sonuç :

  • Eğer controllerdan geçmesini istemediğiniz bir istek yapmak istersek custom Route Handler oluşturabiliriz.

  • endpoints.Map belirli bir path için belirli bir metot çalıştırmamıza yarayabilir. Ve endpoints.Map metodu ikinci paramere olarak RequestDelagete döndüren bir metot alır.

Bir dahaki yazımda görüşmek dileğiyle.

En iyi dileklerim ile.

Mustafa Samed Yeyin.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)