locked
Get Controller Name From Filter Context RRS feed

  • Question

  • User82362805 posted

    I need to get controller Name On OnActionExecuting method I have already did in Asp.net MVC 5 but i dont know how do i do with Asp.net core

    Here is MVC Code 

    var descriptor = filterContext.ActionDescriptor;
    				var ActionParameter = filterContext.ActionParameters;
    				var actionName = descriptor.ActionName;
    				var controllerName = descriptor.ControllerDescriptor.ControllerName;

    Thursday, May 31, 2018 8:54 AM

All replies

  • User475983607 posted

    The ASP core docs explain how to use filters.  You should read the docs first...

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#action-filters

    Route data is available in the executing context. 

            public override void OnActionExecuting(ActionExecutingContext context)
            {
                string name = (string)context.RouteData.Values["Controller"];
                base.OnActionExecuting(context);
            }

    It is easier to provide assistance if you post the actual code and explain what you are trying to do at a high level.

    Thursday, May 31, 2018 10:48 AM
  • User1168443798 posted

    Hi AfaqRajput,

    For an other way which is similar with your current code, I suggest you follow steps below:

    1. CustomFilter

        public class CustomFilter : Attribute, IActionFilter
        {
            private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
            public CustomFilter(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
            {
                _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
            }
            public void OnActionExecuted(ActionExecutedContext context)
            {
                var controllerName = ((Microsoft.AspNetCore.Mvc.ControllerBase)context.Controller)
                                        .ControllerContext                                    
                                        .ActionDescriptor
                                        .ControllerName;
    
            }
    
            public void OnActionExecuting(ActionExecutingContext context)
            {
                
            }
        }

    2. Register Filter

                services.AddScoped<CustomFilter>();
    

    3. Use in Controller Action

            [ServiceFilter(typeof(CustomFilter))]
            public IActionResult About()
    

    Best Regards,

    Edward

    Friday, June 1, 2018 2:57 AM
  • User82362805 posted

    Hi Mgebhard i am trying to secure my action method with restricted filter attribute and i have done it mvc 5 but when i mgrated my code from mvc  5 to core 2.0 it does not work and i have read the documentation but unfortunately i did not resolve it Here is my actual restricted class code

    public class RestrictedAttribute : ActionFilterAttribute, IActionFilter
    	{
    		[ValidateInput(false)]
    		void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    		{
    
    			string RefreshSysMeta = WebConfig.GetSysConfig().RefreshCache();
    
    
    			//Add Cookie value to use in User Login and other places
    			WebConfig.setWebsiteCookie();
    
    
    
    			// Check if this action has NotRestricted....this will skip specific method for restricting
    			object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
    			if (attributes.Any(a => a is NotRestrictedAttribute)) return;
    
    
    
    			//Verify User Login Cookkie Value is valid & Re-activate user session
    			UserService _UserService = new UserService();
    			_UserService.CreateSessionByCookie();
    
    
    			if (!Auth.isLogin)
    			{
    				var values = new RouteValueDictionary(new { action = "Login", controller = "User" });
    				values.Add("url", WebConfig.EncryptedAbsoluteURL);
    				filterContext.Result = new RedirectToRouteResult(values);
    				base.OnActionExecuting(filterContext);
    			}
    			else
    			{
    				bool isSkipAuth = false;
    				bool isAllow = false;
    				string param = string.Empty;
    
    				var req = filterContext.HttpContext.Request;
    
    				var descriptor = filterContext.ActionDescriptor;
    				var ActionParameter = filterContext.ActionParameters;
    				var actionName = descriptor.ActionName;
    				var controllerName = descriptor.ControllerDescriptor.ControllerName;
    
    				var type = filterContext.Controller.GetType();
    				//var method = type.GetMethod(actionName);
    				//var returnType = method.ReturnType;
    
    
    
    
    				if (req.AcceptTypes.Contains("text/html")) { }
    				else if (req.AcceptTypes.Contains("application/json"))
    					isSkipAuth = true;
    				else if (req.AcceptTypes.Contains("application/xml") || req.AcceptTypes.Contains("text/xml"))
    					isSkipAuth = true;
    
    
    				if (req.IsAjaxRequest())
    					isSkipAuth = true;
    
    
    				if (actionName == "Restricted" && controllerName == "Home")
    					isSkipAuth = true;
    
    				//Allow all Partial Request to pass through Authentication
    				if (actionName.StartsWith("_"))
    					isSkipAuth = true;
    
    
    				//Enable Full Access to SuperAdmin Group
    				//if (Auth.RoleId == 1)
    				//	isSkipAuth = true;
    
    
    
    
    
    				if (isSkipAuth)
    					return;
    				else
    				{
    
    					///Get List of All QueryString to Append in the URL
    					var queryStringParams = new NameValueCollection(req.QueryString);
    
    					foreach (string x in queryStringParams)
    					{
                            if (controllerName.Equals("Company") && queryStringParams.AllKeys.Length > 1)
                            {
                                if (x.Equals("typ"))
                                {
                                    if (!string.IsNullOrEmpty(param))
                                        param = "&" + param;
                                    param = x + "=" + queryStringParams[x];
    
                                    break;
                                }
                            }
    
                            if (!string.IsNullOrEmpty(param) && !param.Equals("q"))
                            {
                                if (!string.IsNullOrEmpty(param))
                                    param = "&" + param;
                                param = x + "=" + queryStringParams[x];
                            }
    
                            if (!string.IsNullOrEmpty(x) && x.Equals("typ") && controllerName.Equals("Company"))
                            {
                                if (!string.IsNullOrEmpty(param))
                                    param = "&" + param;
                                param = x + "=" + queryStringParams[x];
    
                                break;
                            }
    					}
    					if (!string.IsNullOrEmpty(param))
    						param = "?" + param.ToLower();
    
    
    					SecurityService _serv = new SecurityService();
                        
                        //15 Jan 2015 Comment code
                        string pgIndex = (actionName.ToLower() == "index" ? actionName : "");
                        string pgParameter = !string.IsNullOrEmpty(pgIndex) ? param : "";
                        var getAccessDetail = _serv.VerifyUserAccess(controllerName, pgIndex, pgParameter);
    
                        //var getAccessDetail = _serv.VerifyUserAccess(controllerName, actionName, param);
    					var getModuleDetail = getAccessDetail != null ? getAccessDetail.AppModule : null;
    					var AccessRights = _serv.VerifyPermission(getAccessDetail, getModuleDetail);
    					bool isFullAccess = AccessRights.Where(e => e.Item1.ToLower() == "fullaccess" && e.Item2.ToLower() == "true").Any() ? true : false;
    					isAllow = AccessRights.Where(e => e.Item1.ToLower() == actionName.ToLower() && e.Item2.ToLower() == "true").Any() ? true : false;
    
                        bool isAllowParam = false, VerifyParam = false;  
                        if (!string.IsNullOrEmpty(param))
                        {		//Verify if param is also need to validate then change isAllow accordingly			
                            if (AccessRights.Where(e => (e.Item1.ToLower() == actionName.ToLower() + param || e.Item1.ToLower() == param)).Count() > 0)
                            {
                                VerifyParam = true;
                                isAllowParam = AccessRights.Where(e => (e.Item1.ToLower() == actionName.ToLower() + param || e.Item1.ToLower() == param)).First().Item2.ConvertToBool();
                            }
    
                            if (VerifyParam)
                                isAllow = isAllowParam;
                        }
    					filterContext.Controller.TempData["AccessRights"] = AccessRights;
    
    					if (isFullAccess)
    						isAllow = true;
    
    					if (!isAllow)
    					{
                            if (req.IsAjaxRequest())
                            {
                                filterContext.Controller.TempData["AlertCSS"] = "alert error";
                                filterContext.Controller.TempData["OutputMessage"] = "You are not authorized to perform this action.";
                            }
    
    						var values = new RouteValueDictionary(new { action = "Restricted", controller = "Home" });
    						values.Add("url", controllerName + "/" + actionName + param);
    						values.Add("ref", HttpUtility.HtmlEncode(req.Url.AbsolutePath));
    
    						filterContext.Result = new RedirectToRouteResult(values);
    						base.OnActionExecuting(filterContext);
    					}
    				}
    			}
    
    		}
    
    	}

    And i Call it like this in my controller

       [Restricted]  
        public class DaysController : Controller
        {
            public daysServices daysServices = new daysServices();
            // GET: Days
          
            public ActionResult Days()
            {
                ViewBag.UserName = Auth.UserName;
                ViewBag.issidebar = true;
                return View();
            }
    }

    Friday, June 1, 2018 8:11 AM
  • User1168443798 posted

    Hi AfaqRajput,

    Do you have any issue with steps in my post to implement ActionFilter attribute?

    If you do, please feel free to let me know.

    Best Regards,

    Edward

    Monday, June 4, 2018 5:20 AM
  • User7210971 posted

    Edward Z, thank you very much, just what I needed. I want to control permissions in my web api using that information, and dynamically I check in database if the current user has the rights to access to that option. I use [DisplayName("ActionName")] attribute for any action method that I need to check, and in database I save all those names as the application options.

    Friday, September 13, 2019 3:53 AM
  • User7210971 posted

    Edward Z, thank you very much, just what I needed. I want to control permissions in my web api using that information, and dynamically I check in database if the current user has the rights to access to that option. I use [DisplayName("ActionName")] attribute for any action method that I need to check, and in database I save all those names as the application options.

    Friday, September 13, 2019 3:54 AM