我想在.NET Core应用程序中实现审核日志记录。 像
[HttpPost, Auditing]
public dynamic SomeApiAction()
该属性应该能够在执行前后拦截API调用,以便进行记录。
.net核心中是否有任何这样的机制可以用作框架的一部分?我不想使用任何第三方组件。 请告知。
答案 0 :(得分:0)
您可以像这样使用CustomActionFilter
public class CustomDemoActionFilter : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
var controller = context.Controller as Controller;
if (controller == null) return;
var controllerName = context.RouteData.Values["controller"];
var actionName = context.RouteData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting", controllerName, actionName);
var CurrentUrl = "/" + controllerName + "/" + actionName;
bool IsExists = false;
if(CurrentUrl=="/Home/Index")
{
IsExists=true;
}
else
{
IsExists=false;
}
if (IsExists)
{
//do your conditional coding here.
//context.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" } });
}
else
{
//else your error page
context.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Error" } });
}
//base.OnActionExecuting(context);
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
,只需将此customactionfilter用作操作方法之类的属性,例如
[HttpGet]
[CustomHMISActionFilter]
public IActionResult Registration()
{
//your code here
}
答案 1 :(得分:0)
您可以尝试Audit.WebApi框架中的Audit.NET库。它提供了可配置的基础结构来记录与Asp.NET Core Web API的交互。
例如使用属性:
using Audit.WebApi;
public class UsersController : ApiController
{
[HttpPost]
[AuditApi(IncludeHeaders = true)]
public IHttpActionResult Post()
{
//...
}
}