4

如何在 ASP.NET Web API 套用 ELMAH 錯誤紀錄模組 (2021 年版)

 2 years ago
source link: https://blog.miniasp.com/post/2021/08/18/ASP-NET-Web-API-with-ELMAH-using-Elmah-Contrib-WebApi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
如何在 ASP.NET Web API 套用 ELMAH 錯誤紀錄模組 (2021 年版)

之前寫過好幾篇跟 ELMAH 相關的文章,其中 如何在 ASP.NET MVC 4 套用 ELMAH 錯誤紀錄模組 這篇還沒有過時,但剛在看 如何在 ASP.NET Web API 套用 ELMAH 錯誤紀錄模組 這篇文章時發現,現在有更簡單的設定方法,所以特別撰文分享心得。

安裝 elmah 套件

這個步驟將會安裝 ELMAH 核心的 elmah.corelibrary 套件,以及套用 ELMAH 必要的 Web.config 設定!

Install-Package elmah

預設套用的設定還不少,其中包含:

三個 <system.web> 下的 httpModules 設定:

<httpModules>
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
  <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
</httpModules>

一個 <system.webServer> 下的 validation 設定:

<validation validateIntegratedModeConfiguration="false" />

三個 <system.webServer> 下的 modules 設定:

<modules>
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
  <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>

一個 <elmah> 自訂組態設定,預設會使用記憶體來儲存錯誤記錄以及關閉遠端存取權限

<configSections>
  <sectionGroup name="elmah">
    <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
    <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
    <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
    <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
  </sectionGroup>
</configSections>

<elmah>
  <!--
      See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for
      more information on remote access and securing ELMAH.
  -->
  <security allowRemoteAccess="false" />
</elmah>

一個 <location> 自訂路徑,設定 ELMAH 使用 /elmah.axd 路徑來查看錯誤記錄 (Web UI):

<location path="elmah.axd" inheritInChildApplications="false">
  <system.web>
    <httpHandlers>
      <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
    </httpHandlers>
    <!--
      See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for
      more information on using ASP.NET authorization securing ELMAH.

    <authorization>
      <allow roles="admin" />
      <deny users="*" />
    </authorization>
    -->
  </system.web>
  <system.webServer>
    <handlers>
      <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
    </handlers>
  </system.webServer>
</location>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK