首页 > 解决方案 > 如何在 .Net 5 中使用 Hot Chocolate 在 GraphQL 中修改响应 Cookie

问题描述

我正在使用 Hot Chocolate(.net 5) 构建 GraphQL API,并且需要使用 JWT 令牌添加身份验证。

在 REST API 中,我使用了仅 http cookie 来添加刷新令牌。

var cookieOption = new CookieOptions
{
    HttpOnly = true,
    Expires = DateTime.UtcNow.AddDays(7)
};

Response.Cookies.Append("refreshToken", <refreshToken.Token>, cookieOption);

在我的登录突变中,我无法像在 REST API 中那样访问 HttpResponse。

甚至 Hot Chocolate 的文档也没有关于如何访问 Http 响应的示例或说明。

我非常感谢这方面的任何帮助。

谢谢

标签: graphql.net-5asp.net5hotchocolatecookie-httponly

解决方案


您可以使用 IHttpContextAccessor 访问 HttpContext 并反过来修改 cookie。

public string Foo(string id, [Service] IHttpContextAccessor httpContextAccessor)
{
    if (httpContextAccessor.HttpContext is not null)
    {
        httpContextAccessor.HttpContext.Response.Cookies...
    }
}

https://chillicream.com/docs/hotchocolate/fetching-data/resolvers/#ihttpcontextaccessor


推荐阅读