I've been facing a similar problem. However, the VirtualPathProvider is just too much plumbing to implement for such a small gain - not to mention that it seems like it has the potential to be a bit risky security-wise to implement. I've found two possible work-arounds:
1) Use reflection to get at what you want:
var page = HttpContext.Current.Handler as Page;
string text = "<table><tr><td>Testing!!!</td></tr></table>";
var systemWebAssembly = System.Reflection.Assembly.GetAssembly(typeof(Page));
var virtualPathType = systemWebAssembly.GetTypes().Where(t => t.Name == "VirtualPath").FirstOrDefault(); // Type.GetType("System.Web.VirtualPath");
var createMethod = virtualPathType.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).Where(m => m.Name == "Create" && m.GetParameters().Length == 1).FirstOrDefault();
object virtualPath = createMethod.Invoke(null, new object[]
{
page.AppRelativeVirtualPath
});
var template = (ITemplate)typeof(TemplateParser).GetMethod("ParseTemplate", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Invoke(null, new object[]{text, virtualPath, true});
2) Use a somewhat hacky work-around:
var page = HttpContext.Current.Handler as Page;
string text = "<table><tr><td>Testing!!!</td></tr></table>";
string modifiedText = string.Format("<asp:UpdatePanel runat=\"server\"><ContentTemplate>{0}</ContentTemplate></asp:UpdatePanel>", text);
var control = page.ParseControl(modifiedText);
var updatePanel = control.Controls[0] as UpdatePanel;
var template = updatePanel.ContentTemplate;
I openly admin that neither is a great solution. Ideally, there would be a method in the .Net Framework for this sort of thing. Something like:
public class TemplateParser
{
public static ITemplate ParseTemplate(string content, string virtualPath, bool ignoreParserFilter)
{
return TemplateParser.ParseTemplate(string content, VirtualPath.Create(virtualPath), ignoreParserFilter);
}
}
That would alleviate the whole need to implement the VirtualPathProvider. Maybe we'll see that in ASP.NET vNext :-)