-
HttpContext
在Asp.net 4.x时代,我们通常的做法是通过HttpContext.Current获取当前请求的上下文进而获取到当前的User属性,所以问题的切入点在于我们如何获取当前的HttpContext上下文。
在我们的Aspnet Core应用中,系统是通过注入HttpContext的访问器对象IHttpContextAccessor来获取当前的HttpContext。
- 参考资源:
- https://www.cnblogs.com/linezero/p/6801602.html(未经验证)
- https://www.cnblogs.com/lex-wu/p/10528109.html(未经验证)
- 参考OrchardCore:srcOrchardCoreOrchardCoreModulesDefaultOrchardHelper.cs
- 首先要在程序启动时注册到容器中HttpContextAccessor
/// <summary> /// Register HttpContextAccessor /// </summary> /// <param name="services">Collection of service descriptors</param> public static void AddHttpContextAccessor(this IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
- Controllers因为引用了Microsoft.AspNetCore.Mvc;命令空间可以直接使用
public virtual IActionResult GeneralCommon() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageSettings)) return AccessDeniedView(); //prepare model var model = _settingModelFactory.PrepareGeneralCommonSettingsModel(); //notify admin that CSS bundling is not allowed in virtual directories if (model.MinificationSettings.EnableCssBundling && HttpContext.Request.PathBase.HasValue) _notificationService.WarningNotification(_localizationService.GetResource("Admin.Configuration.Settings.GeneralCommon.EnableCssBundling.Warning")); return View(model); }
- 中间件中使用HttpContext
public Task Invoke(Microsoft.AspNetCore.Http.HttpContext context, IWebHelper webHelper, IWorkContext workContext) { //set culture SetWorkingCulture(webHelper, workContext); //call the next middleware in the request pipeline return _next(context); }
- 其他层则需要由容器注入后再使用,可以参考以下OrchardCore对HttpContent的定义和调用。
namespace OrchardCore.Modules { public class DefaultOrchardHelper : IOrchardHelper { public DefaultOrchardHelper(IHttpContextAccessor httpContextAccessor) { HttpContext = httpContextAccessor.HttpContext; } public HttpContext HttpContext { get; set; } } }