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

三世轮回 提交于 2020-07-09 12:05:38

问题


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:


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.



来源:https://stackoverflow.com/questions/62653589/is-it-possible-to-retrieve-controllers-action-result-from-net-core-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!