我想在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。