ASP.NET Core中怎么在ExceptionFilter异常过滤器中调用EF Core保存数据到数据库

参考代码:

using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System; 
using System.Linq; 

namespace MatrixWebApiCore.Common.Data
{
    public class DataContext : DbContext
    {

        public DataContext(DbContextOptions options)
      : base(options)
        { }


        /// 
        /// 报告实体,执行增删改查用
        /// 
        public virtual DbSet GroupCharts { get; set; }
        public virtual DbSet CombinationGroupCharts { get; set; }
        /// 
        /// 异常日志
        /// 
        public virtual DbSet Log { get; set; }        
    }   
}


 public class ExceptionFilter : IExceptionFilter
{
   public void OnException(ExceptionContext context)
   {
        //方式一,不推荐这样写
		//var builder = new DbContextOptionsBuilder();
		//builder.UseSqlServer("数据库连接字符串");
		//DataContext dataContext = new DataContext(builder.Options);
		
        //方式二,推荐,获取Startup.cs里面已经注册的实例
        IWebHost host = Program.BuildWebHost(null);                   
        IServiceScope scope = host.Services.CreateScope();
        ILogRepository _logRepository = scope.ServiceProvider.GetService();
        DataContext _dataContext = scope.ServiceProvider.GetService();     

		ILogRepository logRepository = new LogRepository(dataContext);
		ILogRepository logRepository = new LogRepository();
		Log log = new Log();
		log.Id = Guid.NewGuid();
		log.RequestURL = url;
		log.LogTxt = context.Exception.ToString();
		log.CreateTime = DateTime.Now;
		_logRepository.Add(log);
		scope.Dispose();
	}
}

注册过滤器

 services.AddMvc(options =>
            {
                options.Filters.Add();
            });

你可能感兴趣的:(EF,Core,asp.net,core)