[英]How can I make my console application more reusable across different databases?
[英]How can I make my code more reusable for logging in my controllers
我為每個控制器使用相同的代碼。 每次執行操作之前都會調用 OnActionExecuting。 我如何重構給定的代碼?
public class HomeController : Controller
{
private readonly ILogger<AccountController> logger;
private string userId;
private string path;
public AccountController(
ILogger<AccountController> logger)
{
this.logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
userId = User.FindFirstValue(ClaimTypes.NameIdentifier)
path = $"{context.HttpContext.Request.Path.Value}[{context.HttpContext.Request.Method}]";
logger.LogDebug($"{path} started. User(id): {userId}.");
}
}
我如何使用它的示例:
logger.LogInformation($"{path} Was approved for User(id) + {userId}.");
首先,創建一個 BaseController :
public class BaseController : Controller
{
private readonly ILogger<BaseController> logger;
private string userId;
private string path;
public BaseController(IServiceProvider serviceProvider)
{
this.logger = serviceProvider.GetRequiredService<ILogger<BaseController>>();
}
public override void OnActionExecuting(ActionExecutingContext context)
{
userId = User.FindFirstValue(ClaimTypes.NameIdentifier)
path = $"{context.HttpContext.Request.Path.Value}[{context.HttpContext.Request.Method}]";
logger.LogDebug($"{path} started. User(id): {userId}.");
}
}
然后,創建 HomeController
public class HomeController : BaseController
{
public HomeController(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.