![](/img/trans.png)
[英]How pass the TempData in ExceptionFilterAttribute in Asp.Net Core
[英]Access Controller from ExceptionFilterAttribute in ASP.NET Core
使用 ASP.Net Core 2,您如何訪問應用了 ExceptionFilterAttribute 的 Controller 實例?
現在在 Core 中是否有更好的方法來實現共享的“基礎”controller 屬性和方法等? 比如像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();
}
}
ASP.Net Core中的HttpContext
包含IDictionary<object, object>
類的Items
屬性,用於在請求范圍內共享數據。 這正是您覆蓋案件所需要的。 這是一個示例實現:
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();
}
}
}
如果您使用的是 .NET 6 或更高版本,請在此處查看我的回答。 我提供了一個示例,說明如何結合使用 Microsoft.AspNetCore.Mvc.Filters.IActionFilter 和 Microsoft.AspNetCore.Mvc.Filters.IExceptionFilter 來訪問 controller。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.