• net4.x MVC架构迁移到asp.net core的HttpContext问题


    • HttpContext

    在Asp.net 4.x时代,我们通常的做法是通过HttpContext.Current获取当前请求的上下文进而获取到当前的User属性,所以问题的切入点在于我们如何获取当前的HttpContext上下文。

      在我们的Aspnet Core应用中,系统是通过注入HttpContext的访问器对象IHttpContextAccessor来获取当前的HttpContext。

    •  首先要在程序启动时注册到容器中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; }
        }
    }

    
    
    
     
  • 相关阅读:
    线程
    数据类型转换
    复合赋值运算符
    算数运算符
    apache自带的ab压力测试工具用法详解
    创建一个方便快捷实验环境快照
    安装中文版cacti监控华为交换机流量并实现95计费
    虚拟机拷贝后网卡eth0变成了eth1的解决办法
    解压版Tomcat配置
    PLSQL不好用,提示ora-12514 错误解决方法
  • 原文地址:https://www.cnblogs.com/gougou1981/p/12307942.html
Copyright © 2020-2023  润新知