使用ASP.Net Core 2,您如何才能访问应用ExceptionFilterAttribute的Controller实例?
现在在Core中有更好的方法来实现共享的"基础"控制器属性和方法等吗?比如把它放在像Startup这样的更高级别?
在Core之前,在MVC 4中,我会做这样的事情:
/// <summary>
/// Base controller, shared by all WebAPI controllers for tracking and shared properties.
/// </summary>
[ApiTracking]
[ApiException]
public class BaseApiController : ApiController
{
private Common.Models.Tracking _Tracking = null;
public Common.Models.Tracking Tracking
{
get
{
if(_Tracking == null)
_Tracking = new Common.Models.Tracking();
return _Tracking;
}
}
//... other shared properties...
}
/// <summary>
/// Error handler for webapi calls. Adds tracking to base controller.
/// </summary>
public class ApiExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext cntxt)
{
BaseApiController ctrl = cntxt.ActionContext.ControllerContext.Controller as BaseApiController;
if (ctrl != null)
ctrl.Tracking.Exception(cntxt.Exception, true);
base.OnException(actionExecutedContext);
}
}
/// <summary>
/// Intercepts all requests to inject tracking detail and call tracking.save.
/// </summary>
public class ApiTrackingAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext cntxt)
{
//...add info to tracking
}
public override void OnActionExecuted(HttpActionExecutedContext cntxt)
{
BaseApiController ctrl = cntxt.ActionContext.ControllerContext.Controller as BaseApiController;
if (ctrl != null)
ctrl.Tracking.Save();
}
}
Run Code Online (Sandbox Code Playgroud)
HttpContextASP.Net Core 中包含用于在请求范围内共享数据Items的类型属性。IDictionary<object, object>这正是您承保案件所需的。这是一个示例实现:
public class ApiExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var items = context.HttpContext.Items;
if (items.ContainsKey("Tracking"))
{
Tracking tracking = (Tracking)items["Tracking"];
tracking.Exception(context.Exception, true);
}
base.OnException(context);
}
}
public class ApiTrackingAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var tracking = new Tracking();
//...add info to tracking
context.HttpContext.Items.Add("Tracking", tracking);
}
public override void OnActionExecuted(ActionExecutedContext context)
{
var items = context.HttpContext.Items;
if (items.ContainsKey("Tracking"))
{
Tracking tracking = (Tracking) items["Tracking"];
tracking.Save();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2536 次 |
| 最近记录: |