Can I store a Web UserControl ascx and code behind in database and load it from there?

痴心易碎 提交于 2019-12-11 00:30:41

问题


Is there any way I can store the code of the UserControl in a database table, compile it dynamically or Load it from there ? Means I get a string from database that contains the complete code of UserControl and then add it to the page ?


回答1:


A few ideas:

  1. Use UserControl.LoadControl() with temp files
  2. Use UserControl.LoadControl() with HttpHandler
  3. Use BuildManager.CreateInstanceFromVirtualPath() with entire pages (instead of controls)

Option 1: temp files (easiest)

  1. Create a directory for your web application to write to, e.g. ~/tmp/ (and give the web application modify & create permissions to that directory)
  2. Save the UserControl contents to a temp file:

    string userControlContents = /* get user control contents from database */;
    string path = Server.MapPath("~/tmp/2011081612332423.ascx");
    System.IO.File.WriteAllText(path, userControlContents);
    
  3. Load the user control:

    Control c = UserControl.LoadControl("~/tmp/2011081612332423.ascx")
    
  4. Add the user control to the desired page:

    this.Controls.Add(c);
    

Option 2: HttpHandler

  1. Implement a page or HttpHandler that gets the UserControl contents by id and outputs the raw contents from the database to the Response stream
    • This might not work since UserControl.LoadControl() probably doesn't care about the Response stream.
  2. Then load the control as in Option 1:

    Control c = UserControl.LoadControl("~/UserControlFromDB.ascx?id=392")
    
    • ASP.NET JIT caching might break since the file name "UserControlFromDB.ascx" is always the same (only id=NNN changes). URL rewriting might work around this.

Option 3: Compiling pages instead of just controls:

BuildManager.CreateInstanceFromVirtualPath() compiles a Page in ASP.NET from a virtual path. So you could store an entire page in the database and compile it dynamically.


Disclaimer: I don't recommend storing controls or pages in the database; it will increase maintenance, debugging, and security costs.



来源:https://stackoverflow.com/questions/7074232/can-i-store-a-web-usercontrol-ascx-and-code-behind-in-database-and-load-it-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!