如何使用Elmah.带ApiController的MVC
本文关键字:MVC ApiController 何使用 Elmah | 更新日期: 2023-09-27 18:08:59
我需要记录来自ApiController的异常。
安装Elmah后。MVC我可以记录404错误和其他在DB,但在ApiController的异常不显示在Elmah。
有什么办法吗?
<modules>
<remove name="FormsAuthenticationModule" />
<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>
<security allowRemoteAccess="yes" />
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="XXX"/>
</elmah>
public class StatusController : ApiController
{
private StatusBLL statusBLL = new StatusBLL();
// POST api/status
public void Post(StatusDTO status)
{
throw new ArgumentException("test elmah here");
if (!statusBLL.Register(status))
helpers.BusinessLayer.CreateResponseApiMessage(statusBLL.Errors);
}
}
有一个NuGet包:http://www.nuget.org/packages/Elmah.Contrib.WebApi/
安装后,您需要添加一个新的全局过滤器,如下所示:http://blog.elmah.io/logging-to-elmah-io-from-web-api/(只需安装elmah.com contrib . webapi包,不安装elmah.com io)
我已经解决了为Elmah创建自定义属性并将其添加到Global.asax.cs中的问题
public class ElmahErrorAttribute : ExceptionFilterAttribute
{
public override void OnException(
System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
base.OnException(actionExecutedContext);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register); // WebApi
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Configure(System.Web.Http.GlobalConfiguration.Configuration);
}
private void Configure(HttpConfiguration httpConfiguration)
{
httpConfiguration.Filters.Add(
new ElmahErrorAttribute()
);
}
}