rust - 在 FromRequest 实现中获取应用程序状态

标签 rust actix-web

我有一个 actix Web 服务器,我想在 FromRequest 实现中获取服务器的状态。

我尝试过类似的方法:

impl FromRequest for User {
    type Config = ();
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<User, actix_web::Error>>>>;

    fn from_request(req: &HttpRequest, pl: &mut Payload, state: web::Data<State>) -> Self::Future {
       ...
    }
}

但是,当然,这不起作用,因为 from_request 仅要求 2 个参数,而不是 3 个。

最佳答案

你可以这样做:

fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
   let _state = req.app_data::<Data<State>>();
   ....
}

请参阅 app_data 的文档

关于rust - 在 FromRequest 实现中获取应用程序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66106706/

相关文章:

asynchronous - 将请求正文转发到 Actix-Web 中的响应

rust - Actix-Web 中如何获取 IP 地址进行限速?

error-handling - 创建Rust错误填充程序的惯用方式是什么?

iterator - 将装箱值映射到 Rust 中的可变取消引用值

rust - 为什么定义 RUSTFLAGS 会导致 .cargo/config 中的 rustflags 被忽略?

pattern-matching - Rust的比赛早破

rust - 如何将无效的JSON请求正文中的错误描述返回给Rust中的客户端?

rust - 基于迭代器的代码与过程代码 : how to make the iterator-based algorithm faster?

curl - 使用 curl 向 Actix 服务器发送 POST 请求失败,返回 "400 Bad Request"

mongodb - 如果在Rust中使用skip_serialize serde属性,则无法将字段写入MongoDB文档