ar.*_*gin 42 c# asp.net iis httpcontext
我有一个在所有应用程序中使用的值; 我在application_start中设置了它
void Application_Start(object sender, EventArgs e)
{
Dictionary<int, IList<string>> Panels = new Dictionary<int, IList<string>>();
List<clsPanelSetting> setting = clsPanelSettingFactory.GetAll();
foreach (clsPanelSetting panel in setting)
{
Panels.Add(panel.AdminId, new List<string>() { panel.Phone,panel.UserName,panel.Password});
}
Application["Setting"] = Panels;
SmsSchedule we = new SmsSchedule();
we.Run();
}
Run Code Online (Sandbox Code Playgroud)
并在SmsSchedule
public class SmsSchedule : ISchedule
{
public void Run()
{
DateTimeOffset startTime = DateBuilder.FutureDate(2, IntervalUnit.Second);
IJobDetail job = JobBuilder.Create<SmsJob>()
.WithIdentity("job1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1")
.StartAt(startTime)
.WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever())
.Build();
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler sc = sf.GetScheduler();
sc.ScheduleJob(job, trigger);
sc.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
我想在课堂上获得这个价值.(smsjob)
public class SmsJob : IJob
{
public virtual void Execute(IJobExecutionContext context)
{
HttpContext.Current.Application["Setting"];
}
}
Run Code Online (Sandbox Code Playgroud)
但我的问题是:HttpContext.Current为null,为什么HttpContext.Current为null?
编辑: 当我在一个页面的另一个类中使用此代码时它可以工作,但在这个类中我得到错误.
Lex*_* Li 85
显然HttpContext.Current
,null
不仅是您在处理传入请求的线程中访问它.这就是为什么它"在我在一个页面的另一个类中使用此代码时"工作的原因.
它不能在调度相关类中工作,因为相关代码不是在有效线程上执行,而是后台线程,它没有与之关联的HTTP上下文.
总的来说,不要Application["Setting"]
用来存储全局的东西,因为它们并不像你发现的那样是全局的.
如果需要将某些信息传递给业务逻辑层,请将参数作为参数传递给相关方法.不要让你的商业逻辑层访问之类的东西HttpContext
或者Application["Settings"]
作为违反隔离和去耦的原则.
更新:由于引入async/await
它经常发生此类问题,因此您可能会考虑以下提示,
通常,您应该只HttpContext.Current
在几个场景中调用(例如在HTTP模块中).在所有其他情况下,您应该使用
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2而不是HttpContext.Current
.
尝试实现Application_AuthenticateRequest
而不是Application_Start
.
这个方法有一个实例HttpContext.Current
,不像Application_Start
(在应用程序生命周期中很快就会触发,很快就不能保存一个HttpContext.Current
对象).
希望有所帮助.
归档时间: |
|
查看次数: |
91666 次 |
最近记录: |