如何在 .Net 5 中使用 Hot Chocolate 在 GraphQL 中修改响应 Cookie

Posted

技术标签:

【中文标题】如何在 .Net 5 中使用 Hot Chocolate 在 GraphQL 中修改响应 Cookie【英文标题】:How to modify Response Cookie in GraphQL using Hot Chocolate in .Net 5 【发布时间】:2021-12-04 11:55:36 【问题描述】:

我正在使用 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 响应的示例或说明。

我非常感谢任何帮助。

谢谢

【问题讨论】:

【参考方案1】:

您可以使用 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

【讨论】:

以上是关于如何在 .Net 5 中使用 Hot Chocolate 在 GraphQL 中修改响应 Cookie的主要内容,如果未能解决你的问题,请参考以下文章