The Chain of Responsibility allows multiple objects to handle a request without the sender knowing which object will ultimately process it. The request is passed along a "Chain," and each handler decides whether to process it or pass it to the next link.
In ASP.NET Core, every request goes through a pipeline. Authentication -> Routing -> Authorization -> Endpoint. If Authentication fails, it "Short-circuits" and returns a 401. If it succeeds, it calls next().
public void Handle(Request req)
{
if (CanHandle(req))
{
Process(req);
}
else if (_next != null)
{
_next.Handle(req); // Pass to next link in chain
}
}
It follows the Single Responsibility Principle. You can create a LoggingHandler and a SpamCheckHandler as separate classes. You can then reorder them or add new ones at runtime without changing any existing logic.
Q: "How is a Chain of Responsibility different from a Decorator?"
Architect Answer: "Structural vs Behavioral intent. A **Decorator** is about *Adding Functionality* to an object (e.g., adding encryption to a stream). A **Chain of Responsibility** is about *Choosing a Handler* for a request. In a chain, a handler might decide to stop the request entirely (Short-circuiting). In a decorator, the call almost always passes through every single layer of the cake. Decorator is a wrapper; Chain is a pipeline."