我想在webapi項目中實現ELMAH,因爲我對這個elmah技術很陌生,所以我不能實現整個東西。我甚至試圖遵循web中的示例代碼,但是我仍然沒有得到。在web api項目中實現elmah
有人可以幫助我實現與elmah一個適當的工作解決方案。 我會很感激,如果提供了演示目的的可行的解決方案,這將是真正有用的,我聽不懂
我想在webapi項目中實現ELMAH,因爲我對這個elmah技術很陌生,所以我不能實現整個東西。我甚至試圖遵循web中的示例代碼,但是我仍然沒有得到。在web api項目中實現elmah
有人可以幫助我實現與elmah一個適當的工作解決方案。 我會很感激,如果提供了演示目的的可行的解決方案,這將是真正有用的,我聽不懂
下面是使用ELMAH
更新配置文件以使用正確的SMTP設置。下面是配置文件的設置爲例
< security allowRemoteAccess="false" />
< errorMail subject="Production Error - {1}: {0}" smtpServer="server address" from="[email protected]" to="[email protected]" />
創建ExceptionLogger
類。這裏是它使用Web API
public class ElmahExceptionLogger : ExceptionLogger
{
private const string HttpContextBaseKey = "MS_HttpContext";
public override void Log(ExceptionLoggerContext context)
{
// Retrieve the current HttpContext instance for this request.
HttpContext httpContext = GetHttpContext(context.Request);
// Wrap the exception in an HttpUnhandledException so that ELMAH can capture the original error page.
Exception exceptionToRaise = new HttpUnhandledException(message: null, innerException: context.Exception);
ErrorSignal signal;
if (httpContext == null)
{
signal = ErrorSignal.FromCurrentContext();
// Send the exception to ELMAH (for logging, mailing, filtering, etc.).
signal.Raise(exceptionToRaise);
}
else
{
signal = ErrorSignal.FromContext(httpContext);
signal.Raise(exceptionToRaise);
}
}
private static HttpContext GetHttpContext(HttpRequestMessage request)
{
HttpContextBase contextBase = GetHttpContextBase(request);
if (contextBase == null)
{
return null;
}
return ToHttpContext(contextBase);
}
private static HttpContextBase GetHttpContextBase(HttpRequestMessage request)
{
if (request == null)
{
return null;
}
object value;
if (!request.Properties.TryGetValue(HttpContextBaseKey, out value))
{
return null;
}
return value as HttpContextBase;
}
private static HttpContext ToHttpContext(HttpContextBase contextBase){return contextBase.ApplicationInstance.Context; } }
註冊ElmahExceptionLogger
類startup.cs
config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
即使通過@Paresh答案工作的例子,你應該使用Elmah.Contrib.WebApi包,因爲這包括使用ELMAH和Web API所需的一切。
我已經寫了一個指南install ELMAH with Web API。基本上你將安裝ELMAH
和Elmah.Contrib.WebApi
包,然後將其配置是這樣的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
...
}
}
關於郵件配置,您可以使用ELMAH Configuration Validator驗證你的web.config。