是否可以从.NET Core中间件检索控制器的动作结果? [英] Is it possible to retrieve controller's action result from .NET Core middleware?

查看:216
本文介绍了是否可以从.NET Core中间件检索控制器的动作结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

是.但是您不能在控制器中创建新客户端.尝试在Client中创建一个公共变量,您可以在中间件中提供该值.在您的控制器中,您可以获取该值并将其添加到该对象.

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.

这篇关于是否可以从.NET Core中间件检索控制器的动作结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆