MVC and MVC Core how to get the controller name and the name of the filter in Action

Original: MVC and MVC Core how to get the controller name and the name of the filter in Action

Many times we need to use filters to achieve some interception, validation behavior, then we can get to the Context is ActionExecutingContext, how do we get Action, Controller and other objects through the Context of it? record:

In the code

Copy the code
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ViewLogAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
    }
}
Copy the code

More concise way:

var areaName = filterContext.ActionDescriptor.RouteValues["area"];

var controllerName = filterContext.ActionDescriptor.RouteValues["controller"];

var actionName = filterContext.ActionDescriptor.RouteValuse["action"];

1. Name Code acquisition controller 

In MVC

var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

The force required to turn the MVC Core

var controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor).ControllerName;

Or use

filterContext.Controller.GetType().Name

MVC also be

var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"];

2. Obtain Action Name Code

var actionName = filterContext.ActionDescriptor.ActionName;

 or

var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["Action"];

 3. Get Action parameter name

// Get parameter array 
var arrParameter filterContext.ActionDescriptor.GetParameters = (); 
// get the index corresponding to the parameter name 
var paramName = arrParameter [0] .ParameterName ;

4. Get the value of the parameter

var parameterValue = filterContext.Controller.ValueProvider.GetValue(paramName).RawValue;

If determined parameter name may be obtained by direct ActionParameters by Key, Key refers to the parameter name

var parameterValue = filterContext.ActionParameters["KeyName"];

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11988586.html