【问题标题】:In the actix-web rust web framework, is the current StatusCode available in the middleware?在actix-web rust web框架中,当前的StatusCode在中间件中是否可用?
【发布时间】:2021-10-16 00:43:18
【问题描述】:

我正在使用 actix-web 3。我想从 Actix-web 的中间件系统中访问当前状态码。

我想根据状态码修改请求,可以吗?

例如,如果用户发送一些数据导致 actix-web 生成 413 代码,我想修改请求。 我可以通过使用 actix_web::middleware::errhandlers::ErrorHandlers 的处理程序来修改响应,但这些处理程序只有 mut res: actix_web::dev::ServiceResponse 作为它们的参数,似乎我无法找到方法从这些处理程序中访问 actix_web::dev::ServiceRequest 对象。

我希望使用基本中间件,因为中间件中提供了 actix_web::dev::ServiceRequest 和 actix_web::dev::ServiceResponse 对象。

【问题讨论】:

    标签: actix-web rust-actix


    【解决方案1】:

    我似乎忘记了中间件是如何工作的。

    状态码可以通过使用 HttpResponse 对象的 status() 方法从中间件代码中获取。 实现 actix_web::dev::Service trait 的代码可以访问 HttpResponse,如下所示。

    由于状态是发送请求后产生的,因此无法事先知道状态从而修改请求。

            let fut = self.service.call(req);
    
            Box::pin(
                async move
                {
                    let res = fut.await?;
        
                    println!("Hi from response, res.status is:'{}'",res.status());
                    Ok(res)
                }
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-12
      • 2021-08-20
      • 2021-10-14
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      相关资源
      最近更新 更多