BendEg
BendEg

Reputation: 21088

Embed Global.asax in assembly

Is it possible to embed the Global.asax file into an assembly? Currently it is represented as a file in the web root directory. But I want to store it as a resource in an assembly.

Upvotes: 1

Views: 850

Answers (3)

frontlinebg
frontlinebg

Reputation: 463

Yes you can. You have three options as far as I know:

  1. Use HttpModule but be aware that there are some tricky parts about it. For example the HttpModule Init method might be triggered multiple times (this is based on the number of application instances in the app pool)
  2. Use OWIN
  3. Alternate the HttpApplication type - this one works best for me but I haven't tested it in too many different situations and framework versions. The only thing you need to do in your assembly is paste the following:

.

using System.Web;
using System.Web.UI;

[assembly: PreApplicationStartMethod(typeof(MyAssembly.MyHttpApplication), nameof(MyAssembly.MyHttpApplication.Application_Register)]
namespace MyAssembly
{
    public class MyHttpApplication : HttpApplication
    {
        public static void Application_Register()
        {
            PageParser.DefaultApplicationBaseType = typeof(MyHttpApplication);
        }

        protected void Application_Start()
        {
            // TODO: Your application startup magic :)
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // TODO: 
        }
    }
}

Trace (or something like that):

  1. System.Web.UI.PageParser.DefaultApplicationBaseType
  2. System.Web.Compilation.BuildManager.GetGlobalAsaxType()
  3. System.Web.HttpApplicationFactory.CompileApplication()

Hope that helps :)

Upvotes: 1

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

Ali Reza Dehdar's answer is correct (just change Compile to Embedded Resource in file's properties) and the result can be seen using a decompiler:

enter image description here

Upvotes: 1

Ali Reza Dehdar
Ali Reza Dehdar

Reputation: 2351

I'm not sure. Have you tried setting Build Action to Embedded Resource? You can do that by selecting the global.asax file and then the option should appear in your property window.

Upvotes: 2

Related Questions