我有一个位于 Controller 顶部的自定义错误属性:
public class JsonExceptionAttribute : HandleErrorAttribute
{
private ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(ExceptionContext errorContext)
{
if (errorContext.ExceptionHandled) return;
if (!errorContext.Action.Attributes.ContainsType(typeof(DontLogPathAttribute)) { // THIS IS PSEUDOCODE
_log.Error($"Oopsie. {HttpContext.Current.Request.Path}");
}
}
}
在我的 Controller 顶部,我只需添加我的属性:
[JsonException]
public class UserController {
public ActionResult JustAnAction{}
[DontLogPath]
public ActionResult SelfService(string myHash, int userId) {}
}
我通常会记录 Api 调用的路径,以防出现错误。但有一些操作我不想这样做。这些情况具有 DontLogPathAttribute
(这只是一个空的属性类)
在 ExceptionHandling (OnException
) 中,我想查明此属性是否存在。但在ExceptionContext中我什至没有找到一个属性来确定当前的Action。
错误日志之前的行是纯伪代码,显示了我想要实现的目标。这可以吗?
(我在 SO 中看到了一些类似的问题,但在这些情况下,它从来都不是必须处理的 ExceptionContext。)
最佳答案
这应该可以完成工作
public override void OnException(ExceptionContext errorContext)
{
string actionName = errorContext.RouteData.Values["action"] as string;
MethodInfo method = errorContext.Controller.GetType().GetMethods()
.FirstOrDefault(x => x.DeclaringType == errorContext.Controller.GetType()
&& x.Name == actionName);
IEnumerable<Attribute> attributes = method.GetCustomAttributes();
//DoStuff
}
关于c# - 从 HandleErrorAttribute 中获取 Action 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48931273/