开发者

Get ASP.NET assembly from OnInit of custom server control?

开发者 https://www.devze.com 2023-04-13 06:11 出处:网络
I\'m trying to build an ASP.NET custom server control which displays version information about the ASP.NET project contai开发者_高级运维ning the page on which the server control is rendered.

I'm trying to build an ASP.NET custom server control which displays version information about the ASP.NET project contai开发者_高级运维ning the page on which the server control is rendered.

What is the C# syntax to get the assembly of that ASP.NET project?

That is, given this OnInit override inside the custom server control's code...

protected override void OnInit(EventArgs e) {
    System.Reflection.Assembly assembly = Foo();
}

... what goes in Foo()?

EDIT: The custom server control is defined in a Class Library project/assembly which is not the ASP.NET project/assembly.


 public Assembly GetPageAssembly()
 {
   var pageType = Page.GetType();
   return Assembly.GetAssembly(pageType.BaseType == null 
                                || pageType.BaseType == typeof (Page)
                                     ? pageType : pageType.BaseType);
 }

No matter where the control's implementation is, a separate dll or the current one, it will be instantiated in a Page class in the end and added to its Controls collection. This Page is accessible via the Page method and, based on this, will find the assembly.
For an .aspx file ( actually a couple of them if more ), ASP .Net creates a dll. If the "Inherit" attribute is set, then the generated class will look something like:

public _Default_aspx : Namespace._Default, IHttpHandler {
}

This dll is different than the one compiled by Visual Studio, the result of an "Web Application Project" and I think you are interested more for the latest. This dll has the "_Default: type, that we see in Visual Studio:

public _Default : System.Web.Page
{
}

So why this short story? When this.Page.GetType() is called from the server control, then, if the Inherit attribute is set, the method will return _Default_aspx type, but is useless for you, since you need the assembly created by Visual Studio and not the one generated by ASP .Net from aspx/ascx files. If the page or the control has Inherit attribute set, then GetType() it suffices.
Knowing the type, a simply call to Assembly.GetAssembly method returns the assembly you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消