【问题标题】:How to get Cookie from Request in Actix 2.0如何从 Actix 2.0 中的请求中获取 Cookie
【发布时间】:2020-10-21 12:02:40
【问题描述】:

我想从请求中获取 cookie 的值。我发现在 Actix 0.x.x 中,cookie 的值可以通过调用获得

fn get_cookie(req: HttpRequest) {
    let cookie = req.cookie("name") <-- Here

    return HttpResponse::Ok()
        .body(
            format!("{}", cookie);
        )
}

我对 Rust 和 Actix 很陌生。目前我正在从声明的函数中解析它,该函数得到HttpRequest.headers()的字符串。我不确定在 Actix 0.x.x 中是否有直接获取 cookie 的方法。

pub fn get_cookie(req: HttpRequest, name: &str) -> String {
    let cookie: Vec<&str> = req
        .headers()
        .get("cookie")
        .unwrap()
        .to_str()
        .unwrap()
        .split("&")
        .collect();

    let auth_token: Vec<&str> = cookie
        .into_iter()
        .filter(|each| {
            let body: Vec<&str> = each.split("=").collect();

            body[0] == name
        })
        .collect();

    let cookie_part: Vec<&str> = auth_token[0].split("=").collect();

    cookie_part[1].to_owned() 
}

【问题讨论】:

  • 对于身份验证,您可能只使用中间件。提供了一个IdentityService,您可以使用CookieIdentityPolicy 对其进行配置,然后使用Identity 提取器在处理程序中获取身份。

标签: rust rust-actix actix-web


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2016-03-17
    • 2019-10-09
    • 2012-06-25
    • 2014-01-15
    相关资源
    最近更新 更多