简体   繁体   中英

Where to place Google Analytics code in ASP.NET web application

I want to find a place to put my Google Analytics code in my ASP.NET web application. I would like to place it somewhere once and not have to copy and paste the code into multiple files. Is there somewhere that I could inject it that I would only have to include it once and all pages would be effected? I am not using MasterPages unfortunately.

Create a base page which inherits from the Page class, and insert it into the head there. Then have all your other pages inherit from the base page :-)

You would either need to have a base page, or put a custom control on each page where you need the script.

In either of those, you can subscribe to the Init event, and then do the following:

protected override void OnInit(EventArgs e)
    {
        var myAnalyticsScript = @"<insert_analytics_script_here>";
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "analyticScript", myAnalyticsScript);
    }

If you choose a base page, you can control which pages the script appears on by not inheriting from the base page. If you choose a control, you do the same by not putting the control on a page.

Create base page for all pages and add google analitics there. Then inherit each new page from this one.

eg

class PageWithGoogleAnalytics : Page
{
    //some actual code to add analytics
}

class MyCustomPage : PageWithGoogleAnalytics {}

Another suggestion, and yes this is a massive hack, but you could write a HttpModule to automatically inject it into the page after the HTML has been generated by ASP.NET but before IIS sends the request down to the browser.

Note: I really wouldn't suggest this option, but it might be your only choice.

You could put it into a page and then include this page everywhere you want to be check. But masterpage is the best for it.

--- updated --

Add following class in your app_code


public class WebsitePageBase : System.Web.UI.Page
{
    public const string analyticsCode = "your script goes here..."
    protected void Page_Load(Object sender, e as EventArgs)
    {
       ClientScript.RegisterStartupScript(Me.GetType(),"__analytics_script",analyticsCode )
    }
}

and when you add a new aspx page you have to inherit from the new base class so for example you are adding default.aspx your back end class should look like:


public partial class _default : WebsitePageBase
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM