asp.net core在其他程序集获取HttpContext

首先在Program.cs中,注册

csharp 复制代码
builder.Services.AddHttpContextAccessor();

Program.cs完整代码:

csharp 复制代码
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using WebReportInfoNetCore7;
using WebReportInfoNetCore7.DataBaseEntity;
using WebReportInfoNetCore7.IBLL;
using WebReportInfoNetCore7.IBLL_impl;
using WebReportInfoNetCore7.IDAO;
using WebReportInfoNetCore7.IDAO_impl;

var builder = WebApplication.CreateBuilder(args);

//依赖注入
builder.Services.AddSingleton<IAh_userDao, Ah_userDao>();
builder.Services.AddSingleton<IUserBll, UserBll>();


// Add services to the container.
builder.Services.AddControllersWithViews(ops => {
    //全局异常过滤器,注册
    ops.Filters.Add<ExceptionFilter>();
})

//Microsoft.AspNetCore.Mvc.NewtonsoftJson
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});

 
builder.Services.AddSession();

//IHttpContextAccessor 在其他程序集中获取HttpContext
builder.Services.AddHttpContextAccessor();

//解决输入页面中文被编码了
builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

var app = builder.Build();

 
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();
app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

AppServicesHelpter.App = app;


//Microsoft.AspNetCore.Session.ISessionStore
//IHttpContextAccessor Accessor = app.Services.GetService<IHttpContextAccessor>();

app.Run();

其他程序集中获取,其他程序集需要引用文件:Microsoft.AspNetCore.Http.Abstractions.dll

文件位置:

C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\7.0.5\ref\net7.0

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using WebReportInfoNetCore7.ViewEntity;
using System.Net.Http;
using System.Runtime.CompilerServices;

namespace WebReportInfoNetCore7.DataBaseEntity
{
    /// <summary>
    /// 依赖注册,获取接口实例
    /// </summary>
    /// 创建时间:2023-10-8 16:03:39 
    public sealed class AppServicesHelpter
    {
        /// <summary>
        /// 程序
        /// </summary>
        public static Microsoft.AspNetCore.Builder.WebApplication App { get; set; }

        /// <summary>
        /// 获取接口实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetServices<T>() where T : notnull
        {
            T instance = App.Services.GetRequiredService<T>();
            return instance;
        }

        /// <summary>
        /// 获取当前登录用户
        /// </summary>
        /// <returns></returns>
        /// 创建时间:2023-10-10 14:48:23, 
        public static Ah_userView CurrentLoginUser()
        {
            Microsoft.AspNetCore.Http.IHttpContextAccessor accessor = App.Services.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
            string json = accessor.HttpContext.Session.GetString("userLogin");
            return Newtonsoft.Json.JsonConvert.DeserializeObject<Ah_userView>(json);
        }

    }
}

微软文档:
https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/http-context?view=aspnetcore-7.0

相关推荐
向宇it22 分钟前
【从零开始入门unity游戏开发之——unity篇01】unity6基础入门开篇——游戏引擎是什么、主流的游戏引擎、为什么选择Unity
开发语言·unity·c#·游戏引擎
wm104324 分钟前
java web springboot
java·spring boot·后端
仰望大佬0071 小时前
Avalonia实例实战五:Carousel自动轮播图
数据库·microsoft·c#
糖朝1 小时前
c#读取json
c#·json
龙少95432 小时前
【深入理解@EnableCaching】
java·后端·spring
溟洵4 小时前
Linux下学【MySQL】表中插入和查询的进阶操作(配实操图和SQL语句通俗易懂)
linux·运维·数据库·后端·sql·mysql
向宇it6 小时前
【从零开始入门unity游戏开发之——C#篇26】C#面向对象动态多态——接口(Interface)、接口里氏替换原则、密封方法(`sealed` )
java·开发语言·unity·c#·游戏引擎·里氏替换原则
SomeB1oody6 小时前
【Rust自学】6.1. 定义枚举
开发语言·后端·rust
SomeB1oody7 小时前
【Rust自学】5.3. struct的方法(Method)
开发语言·后端·rust
啦啦右一8 小时前
Spring Boot | (一)Spring开发环境构建
spring boot·后端·spring