locked
Global.asax And HttpWebRequest RRS feed

  • Question

  • User-472469351 posted

    Hi Guys,

    I want to execute an asp.net page just once, each time before a Page_Load event is triggered on any of my asp.net pages in my project. I figured for this I may need to call to global.asax and some of its methods. I decided to use Application_EndRequest -> OK, it works, BUT the page I am calling has a javascript that does a post back, and this post back is never rised? Also I get an error saying that the page has been closed forcibly and it couldn't read the response stream.

    protected void Application_EndRequest(Object sender, EventArgs e)

    {

             string lcUrl = http://localhost/WebSite/Test.aspx; HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(lcUrl);

             string lcPostData = "PageTraceInfo=" + HttpUtility.UrlEncode(sPage); loHttp.Method = "POST"; byte[] lbPostBuffer = System.Text.

             Encoding.GetEncoding(1252).GetBytes(lcPostData);  loHttp.ContentLength = lbPostBuffer.Length; Stream loPostData = loHttp.GetRequestStream();

             loPostData.Write(lbPostBuffer, 0, lbPostBuffer.Length); loPostData.Close(); HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();

            Encoding enc = System.Text.Encoding.GetEncoding(1252); StreamReader loResponseStream = new StreamReader(loWebResponse.GetResponseStream(), enc);

            string lcHtml = loResponseStream.ReadToEnd(); loWebResponse.Close(); loResponseStream.Close();

    }

    If what I am doing isn't a solution to my problem, can you please recommend me a way of executing and asp.net page before the rendering of each of my project web pages.

    Thanks a million.

    Saturday, March 10, 2007 5:13 AM

All replies

  • User-524013004 posted

    If you want to do something during the Page Load event of every page create a Custom Base Class inherited from System.Web.UI.Page and inherit all your pages from that.

    However, if you need to execute a page (code) during every page load that includes client side javascript then you are going to have to -

    1. Short circuit the current request.
    2. Reply with a page that provides the javascript (postback) and information on the original request.
    3. Capture the common page submit and redirect back to the original page with information that the first step has been accomplished.

    This is going to murder your application performance.

    Are you really sure this is what you want to do at all? I think it is highly unlikely.

    In this instance, maybe if you post your objectives as opposed to your approach you might (will) get a better solution.

    Saturday, March 10, 2007 8:08 PM
  • User-472469351 posted

    My goal is to be able to execute a javascript on each page loading without having to edit all my asp.net or html files. I tried to do some Response.Write and other stuff, but it all went above the <html> tag and ruined the execution of the whole page. So the next thing I did was to create another page where this java is executed and then posted back to C# function, which does some custom logging and redirects back to the original page. I did it with HttpContext.Current.RewritePath() so the visitor wouldn't notice that another page is being executed. OK, for now all works fine, but there was I thing I didn't predicted. I do this rewriting in the global.asax in Application_BeginRequest event, BUT what I didn't predicted was that the webpage triggered this event each time an object on the html page has to be loaded - image, stylesheet, iframe, etc. So I had to put a lot of if statements to figure out when exactly I need to do the rewriting. And this is absolutelly not a solution, because I have to rewrite the global.asax file each time for each of my projects. So still the best solution for me is to find a way set a javascript function that triggers on body load. I tried almost everything, and I lost any hope. Then I tried to do this html background execution thing that I am describing above. Please help.

     Many thanks.

    Sunday, March 11, 2007 6:01 AM
  • User-524013004 posted

    Hopefully this answers your problem. The following will append a Javascript script to a page on first run. Subsequent postbacks will not append and as such run the script. The script in this instance is simply an alert.

    Create a Class in the App_Code Folder called BasePage and replace all the code with the code below. 

    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    /// <summary>
    /// Summary description for BasePage
    /// </summary>
    public class BasePage : Page
    {
        const string jsScriptName = "startupJs";
    
        public BasePage()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
    
            if(!this.ClientScript.IsStartupScriptRegistered(jsScriptName) && !this.IsPostBack){
                String script = this.BuildStartUpScript();
                this.ClientScript.RegisterStartupScript(this.GetType(),jsScriptName,script,true);
            }
        }
        private string BuildStartUpScript() {
    
            return @"alert(""First load"")";
            
        }
    }
    Create a WebPage and inherit from the new Custom BasePage (this is all you need to do in each page). Note that if you are using inline server side script (not encouraged) you can configure this as the base page in the web config.
    Eg - 
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class Default16 : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    }
     
    In the ASPX for this page place an ASP Button Control. Run the project and view the page.
    Text ASPX
     
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default16.aspx.cs" Inherits="Default16" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Button" /></div>
        </form>
    </body>
    </html>
    
     
    Sunday, March 11, 2007 6:41 PM
  • User-472469351 posted

    You didn't get my point. It is very easy to do if I have to edit all of my asp.net pages. But what if there are pages in html, or other format, and what if there are 1000 of them? I want to be able to do this only by rendering to one file - and this defenetely should be the global.asax. My final question is - is this possible at all?

    Many thanks.

    Monday, March 12, 2007 4:39 AM
  • User-524013004 posted

    As the global.asax will only process requests handled by the app and typically html files are not served by your asp.net application the answer would normally be no. It is possible to configure your app to serve all file types, but this is another performance hit. Each page needs some coding if it is to be a meaningful Server Side Page and the example above means a single word edit for each page.

     

    Monday, March 12, 2007 10:19 PM