Is it possible to retrieve controller's action result from .NET Core middleware?

Viewed 532
public class UsersController : APIControllerBase
{
    public UsersController() { }

    public Client Get()
    {
       return new Client()
        {
            ClientID = 1,
            // LastUpdate =  I want to update this field in middleware
        };
    }

    public Client Get(int id)
    {
       return new Client()
        {
            ClientID = id
            // LastUpdate =  I want to update this field in middleware
        };
    }
}

public class SetClientLastUpdateMiddleware
{
    private readonly RequestDelegate next;

    public SetClientLastUpdateMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await next(context);

        // Can I do something like below?
        if(context.ActionResult is Client) ((Client)context.ActionResult).LastUpdate = Date.Now;
    }
}

Please consider above codes. I want to apply a handler for every endpoint. I don't know if middleware is a proper option. What I need is to get the endpoint's action result as its original type and do some update to it. If middleware is not a proper way, any advice would be appreciated.

1 Answers

Yes. But you can't create a NEW client in your controller. Try to create a public variable in Client which you can give the value in the middleware. And in your controller you can get this value and add to this object.

Related