DEV Community

Supraja Tangella
Supraja Tangella

Posted on

๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ๐—ถ๐—ป๐—ด ๐—–๐˜‚๐˜€๐˜๐—ผ๐—บ ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ ๐—ถ๐—ป ๐—”๐—ฆ๐—ฃ.๐—ก๐—˜๐—ง ๐—–๐—ผ๐—ฟ๐—ฒ: ๐—ฅ๐—ฒ๐—ฎ๐—น-๐—ง๐—ถ๐—บ๐—ฒ ๐—œ๐—ฃ ๐—ฅ๐—ฒ๐˜€๐˜๐—ฟ๐—ถ๐—ฐ๐˜๐—ถ๐—ผ๐—ป, ๐—Ÿ๐—ผ๐—ด๐—ด๐—ถ๐—ป๐—ด & ๐—˜๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—›๐—ฎ๐—ป๐—ฑ๐—น๐—ถ๐—ป๐—ด

Today, I worked on implementing ๐—ฐ๐˜‚๐˜€๐˜๐—ผ๐—บ ๐—บ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ in my ASP.NET Core project to improve security, error tracking, and request logging.

๐—ช๐—ต๐—ฎ๐˜ ๐—ถ๐˜€ ๐—–๐˜‚๐˜€๐˜๐—ผ๐—บ ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ?
Custom middleware is user-defined logic that sits in the HTTP request pipeline. It allows developers to handle cross-cutting concerns such as logging, error handling, and access control.

๐—ช๐—ต๐˜† ๐˜‚๐˜€๐—ฒ ๐—–๐˜‚๐˜€๐˜๐—ผ๐—บ ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ?

  • Centralized error handling
  • Security policy enforcement (e.g., IP filtering)
  • Request/response logging
  • Cleaner, modular architecture

๐Ÿ”น ๐—ฃ๐—ฟ๐—ฎ๐—ฐ๐˜๐—ถ๐—ฐ๐—ฎ๐—น ๐—˜๐˜…๐—ฎ๐—บ๐—ฝ๐—น๐—ฒ๐˜€ ๐—œ ๐—œ๐—บ๐—ฝ๐—น๐—ฒ๐—บ๐—ฒ๐—ป๐˜๐—ฒ๐—ฑ:

  1. ๐—œ๐—ฃ ๐—ฅ๐—ฒ๐˜€๐˜๐—ฟ๐—ถ๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ (๐—ฅ๐—ฒ๐˜€๐˜๐—ฟ๐—ถ๐—ฐ๐˜ ๐—ฎ๐—ฐ๐—ฐ๐—ฒ๐˜€๐˜€ ๐˜๐—ผ ๐—ถ๐—ป๐˜๐—ฟ๐—ฎ๐—ป๐—ฒ๐˜ ๐˜‚๐˜€๐—ฒ๐—ฟ๐˜€):

if (!context.Connection.RemoteIpAddress.ToString().StartsWith("192.168"))
{
context.Response.Redirect("/Account/AccessDenied");
return;
}

๐Ÿฎ. ๐—˜๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—›๐—ฎ๐—ป๐—ฑ๐—น๐—ถ๐—ป๐—ด ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ:

try
{
await _next(context);
}
catch (Exception ex)
{
// redirect to error page
context.Response.Redirect("/Home/Error");
}

๐Ÿฏ. ๐—ฅ๐—ฒ๐—พ๐˜‚๐—ฒ๐˜€๐˜ ๐—Ÿ๐—ผ๐—ด๐—ด๐—ถ๐—ป๐—ด ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ:

Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
await _next(context);

These middleware components now keep my project cleaner and maintain better separation of concerns.

๐—›๐—ฎ๐˜ƒ๐—ฒ ๐˜†๐—ผ๐˜‚ ๐˜‚๐˜€๐—ฒ๐—ฑ ๐—ฐ๐˜‚๐˜€๐˜๐—ผ๐—บ ๐—บ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ ๐˜๐—ผ ๐—ฒ๐—ป๐—ณ๐—ผ๐—ฟ๐—ฐ๐—ฒ ๐—ฏ๐˜‚๐˜€๐—ถ๐—ป๐—ฒ๐˜€๐˜€ ๐—ฟ๐˜‚๐—น๐—ฒ๐˜€ ๐—ผ๐—ฟ ๐—ถ๐—บ๐—ฝ๐—ฟ๐—ผ๐˜ƒ๐—ฒ ๐—ฑ๐—ถ๐—ฎ๐—ด๐—ป๐—ผ๐˜€๐˜๐—ถ๐—ฐ๐˜€ ๐—ถ๐—ป ๐˜†๐—ผ๐˜‚๐—ฟ ๐—”๐—ฆ๐—ฃ.๐—ก๐—˜๐—ง ๐—–๐—ผ๐—ฟ๐—ฒ ๐—ฎ๐—ฝ๐—ฝ๐—น๐—ถ๐—ฐ๐—ฎ๐˜๐—ถ๐—ผ๐—ป๐˜€? ๐—›๐—ผ๐˜„ ๐—ฎ๐—ฟ๐—ฒ ๐˜†๐—ผ๐˜‚ ๐—ต๐—ฎ๐—ป๐—ฑ๐—น๐—ถ๐—ป๐—ด ๐—ฐ๐—ผ๐—ป๐—ฐ๐—ฒ๐—ฟ๐—ป๐˜€ ๐—น๐—ถ๐—ธ๐—ฒ ๐—œ๐—ฃ ๐—ณ๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐—ถ๐—ป๐—ด ๐—ผ๐—ฟ ๐—ฐ๐—ฒ๐—ป๐˜๐—ฟ๐—ฎ๐—น๐—ถ๐˜‡๐—ฒ๐—ฑ ๐—น๐—ผ๐—ด๐—ด๐—ถ๐—ป๐—ด?

Top comments (0)