如何在 Ktor (Kotlin) 管道的各个部分之间传递数据

How to pass data between various parts of the pipeline in Ktor (Kotlin)

正在构建一个 API 并在每次路由执行之前使用 intercept(ApplicationCallPipeline.Call){} 到 运行 一些逻辑。我需要将数据从 intercept() 方法传递到被调用的路由,并且 我在 intercept() 中使用 call.attributes.put() 设置数据,如下所示:

val userKey= AttributeKey<User>("userK") call.attributes.put(userKey, userData)

并使用 call.attributes[userKey] 检索 userData 。 发生的情况是 call.attributes[userKey] 仅适用于我设置属性的 intercept() 方法。它在我需要它的路线上不起作用。 它让我 java.lang.IllegalStateException: No instance for key AttributeKey: userK

我想知道我做事的方式是否正确

这是最简单的代码,可重现您所描述的内容:

class KtorTest {

    data class User(val name: String)

    private val userKey = AttributeKey<User>("userK")
    private val expected = "expected name"

    private val module = fun Application.() {
        install(Routing) {
            intercept(ApplicationCallPipeline.Call) {
                println("intercept")
                call.attributes.put(userKey, User(expected))
            }

            get {
                println("call")
                val user = call.attributes[userKey]
                call.respond(user.name)
            }

        }
    }

    @Test fun `pass data`() {
        withTestApplication(module) {
            handleRequest {}.response.content.shouldNotBeNull() shouldBeEqualTo expected
        }
    }

}

我拦截调用,把用户放在属性中,最后在get请求中用用户响应。 测试通过。

您使用的 ktor 版本和引擎是什么?