We have a web-application that uses T4 templates to render pages.
Pages can contain simple things like text etcetera, but they can also contain custom made modules.
These modules rely on the HttpContext.Current
.
However, the T4 Template is processed in a thread/domain different than my webapplication. And that’s why I cannot access the HttpContext.Current
in that process.
I tried to add a property for the HttpContext to the modules, which is set in the pre processing of the template. This introduces a new problem;
The T4 engine requires all classes used by the page to be [Serialized]
. This is no problem, except for the System.Web.HttpContext class which cannot be serialized.
System.Runtime.Serialization.SerializationException: The type System.Web.HttpContext in assembly System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a is not marked serializable.
So, in order to solve the SerializationExeption
we’d add [NonSerialized]
attribute to our property.
[NonSerialized]
protected HttpContext _context = null;
public HttpContext Context
{
get
{
return _context;
}
set
{
_context = value;
}
}
But by the time the template is deserialized and processed, the Context is null
ofcourse, so I get a NullReferenceException
in my module.
Is there a way I can access the current HttpContext
in code called from the template engine?
I also send this question to Microsoft, and there is a very simple solution for it.
In the custom EngineHost there is a function ProvideTemplatingAppDomain
. You have to make sure your Engine returns AppDomain.CurrentDomain
.
In this way, the template will be compiled and ran in the same domain as your webrequest.