2014年6月12日 星期四

將HTML交由ASP.NET處理

 

Tool:Visual Studio 2013 Ultimate
OS:Windows 8.1
IIS : IIS 8
.NET Framework : 4.5.1
Other:ASP.NET Web Forms

若在ASP.NET Web Forms Global.asax註冊Application_BeginRequest事件

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }

    protected void Application_BeginRequest( object sender , EventArgs e ) {
        Response.Write( "Application_BeginRequest" );
    }
</script>

若有一空白的ASPX網頁如下:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>

則執行ASPX時,便會自動印出以下字串,在ASPX執行之前,會先執行Application_BeginRequest事件

image

但相同網站內的HTML檔案則不會有此效果,只要設定HTML由ASP.NET處理就可,我們可以在組態檔加入以下設定

<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.5.1">
      <buildProviders >
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider"   />
      </buildProviders>
    </compilation>
    <httpRuntime targetFramework="4.5.1" />
  </system.web>

  <system.webServer>
    <handlers>
      <add name="test" path="*.html" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="File" preCondition="integratedMode" />
    </handlers>
  </system.webServer>

</configuration>

若有空白HTML如下

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

</body>
</html>

也會跟ASPX一樣有相同效果

image

沒有留言:

總網頁瀏覽量