简体   繁体   English

actix-web app_data 在请求处理程序中始终为 None

[英]actix-web app_data is always None in request handler

I want to register application level data when configuring Actix http server, but when I try to access the data in a request handler with HttpRequest::app_data() I always get None .我想在配置 Actix http 服务器时注册应用程序级数据,但是当我尝试使用HttpRequest::app_data()访问请求处理程序中的数据时,我总是得到None The code below panics in the index request handler at the expect statement.下面的代码在expect语句的index请求处理程序中发生恐慌。 It does work however if I use a String instead of my TestData struct.但是,如果我使用String而不是我的TestData结构,它确实有效。

What am I doing wrong?我究竟做错了什么?

use actix_web::{middleware, web, HttpRequest, Result, Responder, HttpResponse};
use actix_web::{App, HttpServer};
use std::sync::Arc;
#[macro_use]
extern crate log;
extern crate env_logger;


struct TestData {
  host: String
}

pub async fn index(req: HttpRequest) -> impl Responder {
  let td: &TestData = req.app_data().expect("Test data missing in request handler.");
  td.host.clone()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
  std::env::set_var("RUST_LOG", 
                    format!("actix_server={log_level},actix_web={log_level}", 
                            log_level="DEBUG"));
  env_logger::init();

  let server_data = web::Data::new(
    TestData {
      host: "Dadada".to_string(),
    }
  );

  HttpServer::new(move || {
     App::new()
      .app_data(server_data.clone())
      .route("/", web::get().to(index))
      .wrap(middleware::Logger::default())
  })
  .bind("127.0.0.1:8080")?
  .run()
  .await
}

You need to specify the Data<T> type to app_data with turbo fish syntax.您需要使用 turbo fish 语法为app_data指定Data<T>类型。

pub async fn index(req: HttpRequest) -> impl Responder {
  let td: &TestData = req.app_data::<web::Data<TestData>>().expect("Test data missing in request handler.");

  td.host.clone()
}

If you take a look to HttpRequest::app_data defintion, you see that app_data needs this info to desambiguate the get call如果您查看HttpRequest::app_data定义,您会看到app_data需要此信息来消除get调用的歧义

pub fn app_data<T: 'static>(&self) -> Option<&T> {
        for container in self.0.app_data.iter().rev() {
            //Used here ------------------------\/
            if let Some(data) = container.get::<T>() {
                return Some(data);
            }
        }

        None
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 总是返回 Ok HttpResponse 然后在 actix-web 处理程序中工作 - Always return Ok HttpResponse then do work in actix-web handler 无法将 app_data 内容传递给 Actix Web 集成测试中的处理程序方法 - Cannot pass app_data content to handler methods in Actix Web integration tests Rust actix-web:特征 `Handler&lt;_, _&gt;` 未实现 - Rust actix-web: the trait `Handler<_, _>` is not implemented 使用 function 装饰时,如何将 App 数据传递给 actix-web 中的服务路由处理程序 function? - How do I pass App data to service route handler function in actix-web when using function decorations? 将请求正文转发到 Actix-Web 中的响应 - Forward request body to response in Actix-Web actix-web处理程序内的HTTP请求-&gt;一次有多个执行程序:EnterError - HTTP request inside actix-web handler -> Multiple executors at once: EnterError 将数据附加到 Actix-web 中的代理响应 - Append data to proxied response in Actix-web 尝试从actix-web路由处理程序功能内发出请求时出现错误“ BlockingClientInFutureContext” - Error “BlockingClientInFutureContext” when trying to make a request from within an actix-web route handler function Actix-web 2.0 JsonConfig error_handler 不工作 - Actix-web 2.0 JsonConfig error_handler not working 如何从带有客户端的actix-web处理程序向调用者返回错误? - How to return an error to caller from an actix-web handler with client?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM