[英]How to prevent action execution in OnActionExecuting of class that is inhereted from the Controller
[英]During OnActionExecuting for Web API call - How to map to controller/action class from route string to read action attributes
如何將傳入的路由字符串(例如Products / GetProduct)映射到將被調用的Controller / Method(ProductsController,GetProduct方法)?
我的目標是檢查ProductsContoller的實例,以找到放置在GetProduct方法上的自定義屬性。
一旦知道要處理的是哪種班級/方法,我就知道如何檢查班級。
我曾考慮過只拆分字符串,所以最終得到的是“ Products”和“ GetProducts”,然后我可以尋找一個ProductsController,在其中尋找一個名為GetProducts的方法。
這可能有效,但似乎應該有一個更好的解決方案。 有任何想法嗎?
您可以使用以下命令獲取操作上的實際控制器實例和屬性:
public class Somefilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var controller = actionContext.ControllerContext.Controller;
var someFilterattributes = actionContext.ActionDescriptor.GetCustomAttributes<Somefilter>()
var otherAttributes = actionContext.ActionDescriptor.GetCustomAttributes<Other>()
}
}
其他是對操作的其他過濾器。
您可以通過在OnActionExecuting方法中使用以下代碼來獲取控制器名稱
var controller = actionContext.Request.GetRouteData().Values["controller"];
在Web API中獲取控制器名稱和操作:
Public Class MyClassActionFilter
Inherits ActionFilterAttribute
Public Overrides Sub OnActionExecuted(contexto As HttpActionExecutedContext)
contexto.Request.Properties.Item("MS_HttpRouteData").Values("controller")
contexto.Request.Properties.Item("MS_HttpRouteData").Values("action")
End Sub
Public Sub New
End Sub
End Class
在WebApiConfig.vb中添加一個全局過濾器,因此您無需在所有方法的標題中添加標簽
GlobalConfiguration.Configuration.Filters.Add(New MyClassActionFilter())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.