获取Startup中注入的接口,在Program里Main的时候赋值上,后面在过滤器直接调用。
public class Program
{
public static IBrowseRecordsService _IBrowseRecordsService { get; set; }
public static IBrowseRecordsService BuildBrowseRecordsService()
{
IWebHost host = Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(null)
.ConfigureAppConfiguration(config =>
{
config.AddJsonFile("appsettings.json");
})
.UseStartup<Startup>()
.Build();
IServiceScope scope = host.Services.CreateScope();
IBrowseRecordsService _IBrowseRecordsService = scope.ServiceProvider.GetService<IBrowseRecordsService>();
return _IBrowseRecordsService;
}
public static void Main(string[] args)
{
_IBrowseRecordsService = BuildBrowseRecordsService();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
过滤器:
/// <summary>
/// 浏览记录
/// </summary>
public class BrowseRecordsAttribute : ActionFilterAttribute
{
public string title { get; set; }
public BrowseRecordsAttribute(string _title)
{
title = _title;
}
public override void OnActionExecuted(ActionExecutedContext context)
{
//base.OnActionExecuted(context);
var RequestPath = context.HttpContext.Request.Path;
var UserID = context.HttpContext.Request.Cookies["id"].ToString().DecryptString();
var UserName = context.HttpContext.Request.Cookies["username"].ToString().DecryptString();
var RequestRemoteIp = (context.HttpContext.Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString() + ":" + context.HttpContext.Request.HttpContext.Connection.RemotePort);
var ResponseStatusCode = context.HttpContext.Response.StatusCode == 200 ? true : false;
IBrowseRecordsService _IBrowseRecordsService = Program._IBrowseRecordsService;
_IBrowseRecordsService.Insert(title, RequestPath, UserID, UserName, RequestRemoteIp, ResponseStatusCode);
}
}
[BrowseRecordsAttribute("XX管理")]
public IActionResult Index()
{
return View();
}
PS:当时在过滤器中每次执行一次就调用下面方法来获取接口,页面会先死一次,再加载出来,很恶心,偶尔还会503
IWebHost host = Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(null)
.ConfigureAppConfiguration(config =>
{
config.AddJsonFile("appsettings.json"); //从json.json中读取配置文件 通过配置读取 参数为null下面一句要注释了
//config.AddCommandLine(args); //从命令行中读取配置文件
})
.UseStartup<Startup>()
.Build();
IServiceScope scope = host.Services.CreateScope();
IBrowseRecordsService _IBrowseRecordsService = scope.ServiceProvider.GetService<IBrowseRecordsService>();