简体   繁体   中英

During OnActionExecuting for Web API call - How to map to controller/action class from route string to read action attributes

How can I map the incoming route string (eg Products/GetProduct) to the Controller/Method that will be called (the ProductsController, GetProduct method)?

My goal is to inspect an instance of the ProductsContoller to find a custom attribute put on the GetProduct method.

I know how to inspect the class once I know which which class/method I'm dealing with.

I had considered just splitting the string, so you'd end up with "Products", and "GetProducts", then I can look for a ProductsController, and within that, a method called GetProducts.

This might work, but seems like there should be a better solution. Any ideas?

You can get the actual controller instance and attributes on the action using:

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>()
        }
    }

Where Other is some other filter on the action.

您可以通过在OnActionExecuting方法中使用以下代码来获取控制器名称

var controller = actionContext.Request.GetRouteData().Values["controller"];

In Web API to get controller name and action:

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

In WebApiConfig.vb add a global filter so you do not need to add the tag in the header of all methods

GlobalConfiguration.Configuration.Filters.Add(New MyClassActionFilter())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM