.Net 5中使用Hot Chocolate搭建GraphQL时如何修改Response Cookie
步骤1:注册Http上下文访问服务
在Startup.cs的ConfigureServices方法中添加IHttpContextAccessor的注册,这样才能在GraphQL的Resolver中访问到Http相关对象:
public void ConfigureServices(IServiceCollection services) { // 你的其他服务注册,比如数据库、身份认证服务、Hot Chocolate服务等省略 services.AddHttpContextAccessor(); services.AddGraphQLServer() // 你的Hot Chocolate配置,比如添加Query、Mutation、授权中间件等省略 ; }
步骤2:在登录Mutation中注入IHttpContextAccessor设置Cookie
你可以通过构造函数注入或者方法参数注入两种方式获取IHttpContextAccessor实例,拿到HttpResponse对象后就可以和REST场景一样设置Cookie:
方式1:构造函数注入(推荐复用场景)
public class UserMutation { private readonly IHttpContextAccessor _httpContextAccessor; public UserMutation(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public async Task<LoginResult> LoginAsync(string username, string password) { // 账号密码校验、JWT访问令牌生成、刷新令牌生成逻辑省略 var refreshToken = GenerateRefreshToken(); var cookieOption = new CookieOptions { HttpOnly = true, Expires = DateTime.UtcNow.AddDays(7), // 生产环境建议补充以下安全配置 Secure = true, SameSite = SameSiteMode.Strict, Path = "/" }; // 设置响应Cookie _httpContextAccessor.HttpContext.Response.Cookies.Append("refreshToken", refreshToken.Token, cookieOption); // 返回登录结果,比如访问令牌、过期时间等 return new LoginResult { AccessToken = GeneratedAccessToken, ExpiresIn = 3600 }; } }
方式2:方法参数注入(适合单Resolver使用场景)
如果只有登录Resolver需要用到IHttpContextAccessor,可以直接通过Hot Chocolate的服务注入特性在方法参数中获取:
public async Task<LoginResult> LoginAsync(string username, string password, [Service] IHttpContextAccessor httpContextAccessor) { // 业务逻辑、Cookie设置逻辑和方式1完全一致 }
注意事项
- 中间件配置顺序必须正确,身份认证、授权中间件要放在Hot Chocolate中间件之前,
Startup.cs的Configure方法示例:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 其他中间件比如异常处理、静态文件、CORS等省略 app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGraphQL(); }); }
内容的提问来源于stack exchange,提问作者Ash
相关产品推荐
相关产品推荐

