.NET Core传递HttpContext到BL后Session方法丢失问题求助
问题解决步骤
直接解决「方法不存在」问题
- 确保业务逻辑层(BL)项目已安装
Microsoft.AspNetCore.SessionNuGet包——SetString是ISession的扩展方法,Web项目默认已引用该包,但BL项目通常不会自动包含。 - 在BL层的代码文件顶部添加命名空间引用:
缺少这个命名空间时,编译器无法识别using Microsoft.AspNetCore.Http;SetString这类扩展方法。
架构优化建议(避免强耦合)
直接传递HttpContext或IHttpContextAccessor到BL层会导致业务逻辑与Web层强耦合,难以开展单元测试,建议通过封装Session服务解耦:
在BL层定义Session操作接口:
public interface ISessionService { void SetString(string key, string value); string GetString(string key); // 根据业务需求添加其他Session操作方法 }在Web层实现该接口:
using Microsoft.AspNetCore.Http; public class SessionService : ISessionService { private readonly IHttpContextAccessor _httpContextAccessor; public SessionService(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public void SetString(string key, string value) { _httpContextAccessor.HttpContext?.Session.SetString(key, value); } public string GetString(string key) { return _httpContextAccessor.HttpContext?.Session.GetString(key); } }在Program.cs中注册服务:
builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped<ISessionService, SessionService>();BL层通过依赖注入使用
ISessionService,无需直接依赖HttpContext:public class SomeBL { private readonly ISessionService _sessionService; public SomeBL(ISessionService sessionService) { _sessionService = sessionService; } public async Task<bool> DoSomeWork(int id) { _sessionService.SetString("SomeKey", "SomeValue"); // 执行其他业务逻辑 return true; } }
内容的提问来源于stack exchange,提问作者mudale
相关产品推荐
相关产品推荐

