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)