Application_Begin请求在发布时根本不触发

问题描述

在本地运行时,此代码运行良好。但是,当我以“发布”模式发布文件并将其放置在服务器上的wwwroot文件夹中时,该应用程序会运行,但Application_Begin Request方法永远不会触发。我通过创建一个简单的文本文件对其进行了测试。

编辑:我刚刚在Application_Start()方法中创建了一个简单的异常,并且该异常也不会触发。所以我的global.asax没有启动。这就是我的wwwroot文件夹中的内容

  1. 区域文件夹(帮助文件
  2. Bin文件夹(所有dll和项目文件
  3. Global.asax
  4. packages.config(nuget)
  5. web.config

这是application_start()

 protected void Application_Start()
        {
            AreaRegistration.RegisterallAreas();
            UnityConfig.RegisterComponents();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            var config = GlobalConfiguration.Configuration;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
            CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
            var location = HttpContext.Current.Server.MapPath("~");
            var file = string.Concat(location,"/data.txt");
            using (var tw = new StreamWriter(file,true))
            {
                tw.WriteLine("Begin Request");
                tw.Close();
            }

            throw new Exception();               

        }

我不确定这是dll还是我缺少的东西。我正在使用.Net 4.7.2

 protected void Application_BeginRequest()
        {
            var location = HttpContext.Current.Server.MapPath("~");
            var file = string.Concat(location,true))
            {
                tw.WriteLine("Begin Request");
                tw.Close();
            }
            if (Request.Headers.AllKeys.Contains("Origin",StringComparer.OrdinalIgnoreCase) &&
                 Request.HttpMethod == "OPTIONS")
            {
                using (var tw = new StreamWriter(file,true))
                {
                    tw.WriteLine("Options Hit");
                    tw.Close();
                }
                Response.Headers.Add("Access-Control-Allow-Headers","Content-Type,Accept,X-Requested-With,Session,Authorization,USER_NBKID,Role,access-control-allow-credentials");
                HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.OK;
                Response.End();
            }                
        }

我的webconfig也有此部分,但仍然无法正常工作

<system.web>
    <caching>
      <outputCache enableOutputCache="false" />
    </caching>
    <compilation debug="true" targetFramework="4.7.2" />
    <customErrors mode="Off" />
    <authentication mode="None" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    **<modules runAllManagedModulesForAllRequests="true">** <---------------------
      <remove name="FormsAuthentication" />
      <remove name="WebDAVModule" />
    </modules>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="https://www.myaspwebsite.com" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,HEAD" />
        <add name="Access-Control-Allow-Headers" value="access-control-allow-origin,access-control-allow-credentials,Origin,Content-Type,USER_ID,UserRole" />
        <add name="Cache-Control" value="no-cache" />
        <add name="Pragma" value="no-cache" />
        <add name="Expires" value="-1" />
      </customHeaders>
    </httpProtocol>
    <rewrite>
      <outboundRules>
        <clear />
        <rule name="AddCrossDomainHeader">
          <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
            <add input="{HTTP_ORIGIN}" pattern="(https?:\/\/((.+\.)?[a-zA-Z0-9-]*\.ap\.dk|(.+\.)?localhost(\:[0-9]*)?))" />
          </conditions>
          <action type="Rewrite" value="{C:0}" />
        </rule>
      </outboundRules>
    </rewrite>
       <handlers>
        <remove name="WebDAV" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONsverbHandler" />
        <remove name="TRACEVerbHandler" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,DEBUG,PATCH,OPTIONS" modules="IsapiModule" scriptprocessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,OPTIONS" modules="IsapiModule" scriptprocessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      </handlers>   
  </system.webServer>

解决方法

我发现这并没有触发,因为web.config中的这一行不准确

<compilation debug="true" targetFramework="4.7.2" />

4.7.2未安装在服务器上,所以我将其更改为

<compilation debug="true" targetFramework="4.5" />

及其工作。花了三天的时间弄清了这么简单的问题