如何在ASP.NET 5 / vNext / Core中使用Elmah?

问题描述 投票:8回答:2

我对如何在ASP.NET 5 / MVC 6项目中使用Elmah感到有点困惑。我从nuget获得了包,它将"Elmah.Mvc": "2.1.2"添加到project.json中的依赖项中。

我不知道从哪里开始 - 在当天,nuget会在web.config中添加条目,现在已经不见了。我似乎无法在他们的github或其他地方找到任何例子。

我错过了一些简单的事吗?

c# asp.net asp.net-core elmah elmah.mvc
2个回答
14
投票

而不是使用ELMAH,手动实现错误记录并不困难。此过程将捕获项目中发生的任何异常并将其记录到数据库表中。为此,请将以下内容添加到Startup.cs中的Configure方法

  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
  }
  else
  {
    app.UseExceptionHandler(builder =>
      {
        builder.Run(async context =>
        {
          context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
          context.Response.ContentType = "text/html";

          var error = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>();
          if (error != null)
          {
            LogException(error.Error, context);
            await context.Response.WriteAsync("<h2>An error has occured in the website.</h2>").ConfigureAwait(false);
          }
        });
      });
  }

也包括在Startup.cs中:

private void LogException(Exception error, HttpContext context)
{
  try
  {
    var connectionStr = Configuration["ConnectionString"];
    using (var connection = new System.Data.SqlClient.SqlConnection(connectionStr))
    {
      var command = connection.CreateCommand();
      command.CommandText = @"INSERT INTO ErrorLog (Application, Host, Type, Source, Path, Method, Message, StackTrace, [User],  WhenOccured)
    VALUES (@Application, @Host, @Type, @Source, @Path, @Method, @Message, @StackTrace, @User,  @WhenOccured)";
      connection.Open();

      if (error.InnerException != null)
        error = error.InnerException;

      command.Parameters.AddWithValue("@Application", this.GetType().Namespace);
      command.Parameters.AddWithValue("@Host", Environment.MachineName);
      command.Parameters.AddWithValue("@Type", error.GetType().FullName);
      command.Parameters.AddWithValue("@Source", error.Source);
      command.Parameters.AddWithValue("@Path", context.Request.Path.Value);
      command.Parameters.AddWithValue("@Method", context.Request.Method);
      command.Parameters.AddWithValue("@Message", error.Message);
      command.Parameters.AddWithValue("@StackTrace", error.StackTrace);
      var user = context.User.Identity?.Name;
      if (user == null)
        command.Parameters.AddWithValue("@User", DBNull.Value);
      else
        command.Parameters.AddWithValue("@User", user);
      command.Parameters.AddWithValue("@WhenOccured", DateTime.Now);

      command.ExecuteNonQuery();
    }
  }
  catch { }
}

请注意,您必须使用此函数中使用的结构在数据库中创建表。


3
投票

ELMAH尚未更新以支持ASP.NET Core。 Atif Aziz做了一些工作,构建了一个名为Bootstrapper的web.config免费配置模块。 Bootstrapper不支持ASP.NET Core(据我所知)。但我很确定支持新版本的工作将在我们接近RTM时立即开始。

© www.soinside.com 2019 - 2024. All rights reserved.