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

相关推荐
Yaml41 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
小码编匠2 小时前
一款 C# 编写的神经网络计算图框架
后端·神经网络·c#
AskHarries2 小时前
Java字节码增强库ByteBuddy
java·后端
佳佳_2 小时前
Spring Boot 应用启动时打印配置类信息
spring boot·后端
许野平4 小时前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
BiteCode_咬一口代码4 小时前
信息泄露!默认密码的危害,记一次网络安全研究
后端
Envyᥫᩣ5 小时前
C#语言:从入门到精通
开发语言·c#
齐 飞5 小时前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
LunarCod5 小时前
WorkFlow源码剖析——Communicator之TCPServer(中)
后端·workflow·c/c++·网络框架·源码剖析·高性能高并发