.Net 6 在静态类中使用HttpContext,解决HttpContext为null

时间:2025-03-27 20:05:07
public class MyClass { //声明一个 IServiceCollection 接口类 public static IServiceCollection? serviceCollection; //获取到 HttpContext 对象 public static HttpContext Current { get { object factory = serviceCollection.BuildServiceProvider().GetService(typeof(IHttpContextAccessor)); HttpContext context = ((IHttpContextAccessor)factory).HttpContext; return context; } } /// <summary> /// 添加cookie /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="days">过期时间</param> public static void SetCookie(string key, string value,int days=3) { //如果有密钥 进行加密 if (!string.IsNullOrEmpty(secret)) { value= value.MD5Encrypt(secret); } CookieOptions options = new CookieOptions(); options.Expires = DateTime.Now.AddDays(days);//过期时间 Current.Response.Cookies.Append(key, value, options); } public static string Get(string key) { return Current.Request.Cookies[key]; } }