views:

196

answers:

0

I want to add html meta data dynamically to the HEAD element of an aspx-page by using a HttpModule.

When I hook to the PreRequestHandlerExecute event the Header property of the page is null.

When I hook to the PostRequestHandlerExecute event the Header property is available but adding controls to it doesn't seem to work. When debugging, I can find the attached HtmlMeta control, but the rendered page doesn't contain it.

Here my current code:

public class MetaDataHttpModule : System.Web.IHttpModule
{
    public void Dispose()
    {
        //clean up code here
    }

    public void Init(System.Web.HttpApplication context)
    {
        try
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
            context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.TargetSite.ToString() + " in " + ex.TargetSite.DeclaringType.FullName + " failed. Reason:" + System.Environment.NewLine + ex.Message);
        }
    }

    void context_PostRequestHandlerExecute(object sender, EventArgs e)
    {
        GenerateMetaData();
    }

    void context_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        GenerateMetaData();
    }

    private void GenerateMetaData()
    {
        System.Web.UI.Page _Page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page;
        if (_Page != null)
        {
            if (_Page.Header != null)
            {
                System.Web.UI.HtmlControls.HtmlMeta _HtmlMeta = new System.Web.UI.HtmlControls.HtmlMeta();
                _HtmlMeta.Name = "keywords";
                _HtmlMeta.Content = "Hello World";

                _Page.Header.Controls.Add(_HtmlMeta);
            }
        }
    }
}

Thanks for any help. Cheers!