Skip to content

Middleware structure

Latest
Compare
Choose a tag to compare
@stifskere stifskere released this 11 Apr 10:40
0c88496

Description

This release features changes in how the middleware is declared, the class UsesMiddlewareAttribute no longer exists, so the whole "Declare method and use it as middleware" can't be done anymore. To create a middleware, you now must create a class that extends MiddlewareAttribute. This enables you to add custom parameters to your middleware class.

class PrintBeforeRunMiddleware(string message) : MiddlewareAttribute
{
   public override IResponsible Handler(RequestEntity request) 
   {
        Console.WriteLine(message);
        return Middleware.Next;
   }
}

This is a middleware declaration, now to call the next middleware you return a Middleware.Next property access, which internally is a new Middleware() but semantically looks better, now you can use that middleware in your routes.

[RouteGroup("/example")]
public static class ExampleGroup 
{
    [PrintBeforeRunMiddleware("hello")]
    [Route(RequestMethodType.Get, "/route")]
    public static ResponseEntity ExampleRoute(RequestEntity request)
    {
        return new ResponseEntity(ResponseCodes.Ok);
    }
}

Now this route prints "hello" every time it is called.

Changes

As explained before, UsesMiddlewareAttribute no longer exists, this way enabling the use of parameters in middlewares.

+ [CustomMiddleware(...params)]
- [UsesMiddleware(typeof(Type), nameof(Type.Method))]

The route declaring attribute changed its name to RouteAttribute. This being made to avoid confusion on what is a GroupMemberAttribute.

+ [Route(RequestMethodType.Get, "/route")]
- [GroupMember(RequestMethodType.Get, "/route")]

The way you return from middlewares slightly changed now, you need to return a Middleware.Next instead of a new NextMiddleware() this being a simple semantic change, you can access the same methods and properties as before, the API didn't change, only its name and way of instantiation.

+ return Middleware.Next;
- return new NextMiddleware();