我有一个带静态get属性的静态类,在这个属性中,我这样做:
// property body
{
// HttpContext.Current is NOT null
...
Parallel.ForEach(files, file =>
{
// HttpContext.Current is null
var promo = new Promotion();
...
});
...
// HttpContext.Current is NOT null
}
Run Code Online (Sandbox Code Playgroud)
在视图使用此属性之前,此静态类不会进行类型初始化.
问题是,Promotion的静态构造函数,初始化第一次new Promotion()被内创建Parallel.ForEach(),使用HttpContext.Current.何时promo在此范围内实例化Parallel.ForEach(),HttpContext.Current是null,new Promotion()因此导致异常.
HttpContext.Current静态get属性中不为null,因为在视图使用它之前不会调用它(因此有一个HttpContext.Current).
如果Promotion使用HttpContext.Current在它的实例,而不是它的静态成员,我很可能只是传递HttpContext.Current到new Promotion()构造函数:
var context = HttpContext.Current;
Parallel.ForEach(files, file =>
{
var promo = …Run Code Online (Sandbox Code Playgroud) 我创建了一个其他网站可以用来在我的数据库中存储错误的Web服务.然后,他们可以访问我的网站查看他们的错误,搜索错误,过滤错误等.但是,我的Web服务出现以下错误:
System.Web.HttpContext无法序列化,因为它没有无参数构造函数.
描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.
异常详细信息:System.InvalidOperationException:System.Web.HttpContext无法序列化,因为它没有无参数构造函数.
Web服务包含以下功能:
[WebMethod]
public static void LogError(HttpContext context, Exception exception, string APIKey)
{
//Log the error
}
使用Web服务记录异常的外部站点在global.asax文件中包含以下代码:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
WebService.Errors.ErrorHandler.LogError(HttpContext.Current, Server.GetLastError(), "NOLDFHOI");
}
如何从Web站点将HttpContext从其站点获取到我的函数中?
我创建了一个名为MyLongRunningClass包含方法的类:
public string ProcessLongRunningAction(IEnumerable<HttpPostedFileBase> files ,string id)
{
int currentIndex = 0;
foreach (HttpPostedFileBase file in files)
{
currentIndex++;
lock(syncRoot)
{
string path=HttpContext.Current.Server.MapPath("~//Content//images //"+file.FileName);//Excecption is created here........
file.SaveAs(path);
}
Thread.Sleep(300);
}
return id;
}
Run Code Online (Sandbox Code Playgroud)
从控制器调用此方法,使用文件列表保存在images目录中.无论何时HttpContext.Current.Server.MapPath("~//Content//images//"+file.FileName)被执行NullReferenceException抛出,HttpContext.Current总是如此null.当我使用session时会发生同样的事情.我不知道代码有什么问题.