public void GetCanonicalActionsWrapsMethodInfos() { // Arrange Type controllerType = typeof(MyController); MethodInfo mInfo0 = controllerType.GetMethod("AliasedMethod"); MethodInfo mInfo1 = controllerType.GetMethod("NonAliasedMethod"); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType); // Act ActionDescriptor[] aDescsFirstCall = cd.GetCanonicalActions(); ActionDescriptor[] aDescsSecondCall = cd.GetCanonicalActions(); // Assert Assert.AreNotSame(aDescsFirstCall, aDescsSecondCall, "GetCanonicalActions() should return a new array on each invocation."); Assert.IsTrue(aDescsFirstCall.SequenceEqual(aDescsSecondCall), "Array elements were not equal."); Assert.AreEqual(2, aDescsFirstCall.Length); ReflectedActionDescriptor aDesc0 = aDescsFirstCall[0] as ReflectedActionDescriptor; ReflectedActionDescriptor aDesc1 = aDescsFirstCall[1] as ReflectedActionDescriptor; Assert.IsNotNull(aDesc0, "Action 0 should have been of type ReflectedActionDescriptor."); Assert.AreEqual("AliasedMethod", aDesc0.ActionName, "Action 0 Name did not match."); Assert.AreSame(mInfo0, aDesc0.MethodInfo, "Action 0 MethodInfo did not match."); Assert.AreSame(cd, aDesc0.ControllerDescriptor, "Action 0 Controller did not point back to controller descriptor."); Assert.IsNotNull(aDesc1, "Action 1 should have been of type ReflectedActionDescriptor."); Assert.AreEqual("NonAliasedMethod", aDesc1.ActionName, "Action 1 Name did not match."); Assert.AreSame(mInfo1, aDesc1.MethodInfo, "Action 1 MethodInfo did not match."); Assert.AreSame(cd, aDesc1.ControllerDescriptor, "Action 1 Controller did not point back to controller descriptor."); }
public void GetCanonicalActionsWrapsMethodInfos() { // Arrange Type controllerType = typeof(MyController); MethodInfo mInfo0 = controllerType.GetMethod("AliasedMethod"); MethodInfo mInfo1 = controllerType.GetMethod("NonAliasedMethod"); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType); // Act ActionDescriptor[] aDescsFirstCall = cd.GetCanonicalActions(); ActionDescriptor[] aDescsSecondCall = cd.GetCanonicalActions(); // Assert Assert.NotSame(aDescsFirstCall, aDescsSecondCall); Assert.True(aDescsFirstCall.SequenceEqual(aDescsSecondCall)); Assert.Equal(2, aDescsFirstCall.Length); ReflectedActionDescriptor aDesc0 = aDescsFirstCall[0] as ReflectedActionDescriptor; ReflectedActionDescriptor aDesc1 = aDescsFirstCall[1] as ReflectedActionDescriptor; Assert.NotNull(aDesc0); Assert.Equal("AliasedMethod", aDesc0.ActionName); Assert.Same(mInfo0, aDesc0.MethodInfo); Assert.Same(cd, aDesc0.ControllerDescriptor); Assert.NotNull(aDesc1); Assert.Equal("NonAliasedMethod", aDesc1.ActionName); Assert.Same(mInfo1, aDesc1.MethodInfo); Assert.Same(cd, aDesc1.ControllerDescriptor); }
public static IEnumerable <PermissionModel> GetAllActionByAssembly() { var result = new List <PermissionModel>(); // 获取命名空间下所有的类型 var types = Assembly.Load("mvcIdentity").GetTypes(); //取控制器 foreach (var type in types) { if (type.BaseType == typeof(BaseController))//如果是 BaseController 的子类 { //反射控制器 var controller = new ReflectedControllerDescriptor(type); //取控制器的Action,共有实例方法 var actions = controller.GetCanonicalActions(); //构建权限 foreach (var action in actions) { //创建权限 var ap = new PermissionModel() { Action = action.ActionName, Controller = controller.ControllerName, //Params = FormatParams(action), Description = GetDescription(action) }; result.Add(ap); } } } return(result); }
public void EvaluateAjaxRequest(AjaxRequestResult requestResult) { //The easy way requestResult.IsAjaxRequest = (_httpRequest[XRequestedWith] == XmlHttpRequest) || (_httpRequest.Headers[XRequestedWith] == XmlHttpRequest); //If we are not sure that we have an AJAX request or that we have to return JSON //we fall back to Reflection if (!requestResult.IsAjaxRequest) { try { //We create a controller instance var controllerFactory = new DefaultControllerFactory(); var controller = controllerFactory.CreateController(_httpRequest.RequestContext, requestResult.RequestController) as Controller; //We get the controller actions if (controller != null) { var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); var controllerActions = controllerDescriptor.GetCanonicalActions(); //We search for our action if (SeekControllerActionWithJson(requestResult, controllerActions)) { requestResult.IsAjaxRequest = true; } } } catch { } } }
public FilterInfo GetFiltersPublic() { var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TestController)); var actionDescriptor = controllerDescriptor.GetCanonicalActions().Single(x => x.ActionName == "Index"); return(base.GetFilters(new ControllerContext(), actionDescriptor)); }
internal static List <SplitGoal> FindSplitGoals() { var groups = new List <SplitGoal>(); List <Type> allValidControllers = GetAllControllers <AbTestMasterController>(GetAssemblyByName(AbTestMasterBootstrapper.AssmeblyNames)); foreach (var controllerType in allValidControllers) { var currentControllerDescriptor = new ReflectedControllerDescriptor(controllerType); ActionDescriptor[] actions = currentControllerDescriptor.GetCanonicalActions(); string area = GetAreaName(currentControllerDescriptor.ControllerType.FullName); foreach (ActionDescriptor action in actions) { var splitGoalAttributes = action.GetCustomAttributes(typeof(SplitGoalAttribute), false) as SplitGoalAttribute[]; if (splitGoalAttributes != null) { foreach (var splitGoalAttribute in splitGoalAttributes) { groups.Add(new SplitGoal { Goal = splitGoalAttribute.SplitGoal.Goal, Action = action.ActionName, Controller = currentControllerDescriptor.ControllerName, Area = area }); } } } } return(groups); }
override internal IEnumerable <ParameterInfo> GetParameterInformation() { return(_controllerDescriptor .GetCanonicalActions() .SelectMany(action => action.GetParameters() .Select(p => ((ReflectedParameterDescriptor)p).ParameterInfo))); }
/// <summary> /// Find a specific Action in the located Controller based on the name supplied. /// Where multiple Actions of that name exist, use the version that matches the maximum number of available/applicable parameters. /// </summary> /// <param name="controller">The controller containing the action</param> /// <param name="actionName">The Action to find in the controller</param> /// <param name="model">The Model that should be passed to the Action if possible</param> /// <param name="message">The Message that should be passed to the Action if possible</param> /// <returns></returns> private ActionDescriptor FindAction( ControllerBase controller, string actionName, object model = null, object message = null) { // Now get the Metadata about the controller var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); // List all matching actions var actionDescriptor = controllerDescriptor.GetCanonicalActions() .Where( ad => // that have the correct name AND ad.ActionName.ToLower() == actionName.ToLower() && this.HasAcceptableParameters(ad, model, message)) // Now put the largest number of parameters first .OrderByDescending(ad => ad.GetParameters().Count()) // And that the top one .FirstOrDefault(); // If we were able to find it if (actionDescriptor != null) { // Add the action name into the RouteData controller.ControllerContext.RouteData.Values.Add("action", actionName); } return(actionDescriptor); }
/// <summary> /// 使用Descriptor,取程序集中所有Action的元数据 /// </summary> /// <returns></returns> public static IEnumerable <ApplicationPermission> GetAllActionByAssembly() { var result = new List <ApplicationPermission>(); //取程序集中的全部类型 var types = Assembly.Load(Assembly.GetAssembly(typeof(ActionPermissionService)).FullName).GetTypes(); //取控制器 foreach (var type in types) { if (type.BaseType == typeof(BaseAdminController))//如果是BaseController { //反射控制器 var controller = new ReflectedControllerDescriptor(type); //取控制器的Action,共有实例方法 var actions = controller.GetCanonicalActions(); //构建权限 foreach (var action in actions) { //创建权限 var ap = new ApplicationPermission() { Action = action.ActionName, Controller = controller.ControllerName, //Params = FormatParams(action), Description = GetDescription(action) }; result.Add(ap); } } } return(result); }
public List <string> GetMetodosControlador(string controlador) { List <string> NavItems = new List <string>(); ReflectedControllerDescriptor controllerDesc = new ReflectedControllerDescriptor(this.GetType()); foreach (ActionDescriptor action in controllerDesc.GetCanonicalActions()) { bool validAction = true; object[] attributes = action.GetCustomAttributes(false); // Look at each attribute foreach (object filter in attributes) { // Can we navigate to the action? if (/*filter is HttpPostAttribute ||*/ filter is ChildActionOnlyAttribute) { validAction = false; break; } } if (validAction) { NavItems.Add(action.ActionName); } } return(NavItems); }
public void EachPermissionResouceHasValidActionDescriptor() { using (var serviceLocatorFixture = new ServiceLocatorFixture()) { // Arrange SetServiceLocatorFixture(serviceLocatorFixture); //Act var permissionDescriptors = IoC.CurrentContainer.ResolveAll <IPermissionDescriptor>(); var allActionPermissions = new Dictionary <string, List <string> >(); var resources = permissionDescriptors.SelectMany(pd => pd.Resources); foreach (var resource in resources) { var controller = resource.Name; var actions = new List <string>(); if (resource.Resources != null) { foreach (var subResource in resource.Resources.Where(subResource => !actions.Contains(subResource.Name))) { actions.Add(subResource.Name); } } allActionPermissions.Add(controller, actions); } var controllers = IoC.CurrentContainer.ResolveAll <BaseController>(); var allActions = new Dictionary <string, List <string> >(); foreach (var controller in controllers) { var reflectedControllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); var actionDescriptors = reflectedControllerDescriptor.GetCanonicalActions(); var actions = actionDescriptors.Select(actionDescriptor => actionDescriptor.ActionName).ToList(); allActions.Add(controller.GetType().FullName, actions); } foreach (var controllerDescriptor in GetHttpControllerDescriptors(IoC.CurrentContainer.ResolveAll <BaseApiController>())) { var controllerServices = controllerDescriptor.Configuration.Services; var actionMappings = controllerServices.GetActionSelector().GetActionMapping(controllerDescriptor).SelectMany(m => m); var actions = actionMappings.Select(a => a.ActionName).ToList(); allActions.Add(controllerDescriptor.ControllerType.FullName, actions); } //Assert foreach (var permissionAction in allActionPermissions) { foreach (var value in permissionAction.Value) { Assert.IsTrue(allActions.Any(a => a.Key == permissionAction.Key && a.Value.Contains(value))); } } } }
//This method checks if we have an AJAX request or not private bool IsAjaxRequest() { //The easy way bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest") || ((Request.Headers != null) && (Request.Headers["X-Requested-With"] == "XMLHttpRequest")); //If we are not sure that we have an AJAX request or that we have to return JSON //we fall back to Reflection if (!isAjaxRequest) { try { //The controller and action string controllerName = Request.RequestContext. RouteData.Values["controller"].ToString(); string actionName = Request.RequestContext. RouteData.Values["action"].ToString(); //We create a controller instance DefaultControllerFactory controllerFactory = new DefaultControllerFactory(); Controller controller = controllerFactory.CreateController( Request.RequestContext, controllerName) as Controller; //We get the controller actions ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); ActionDescriptor[] controllerActions = controllerDescriptor.GetCanonicalActions(); //We search for our action foreach (ReflectedActionDescriptor actionDescriptor in controllerActions) { if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper())) { //If the action returns JsonResult then we have an AJAX request if (actionDescriptor.MethodInfo.ReturnType .Equals(typeof(JsonResult))) { return(true); } } } } catch (Exception eeee) { log.Exception(eeee); } } return(isAjaxRequest); }
public MvcActionFunction(Type controllerType, string actionName, string @namespace, string name, string description, FunctionCollection functionCollection) : base(@namespace, name, description, functionCollection) { _controllerDescriptor = new ReflectedControllerDescriptor(controllerType); _actionName = actionName; var actions = _controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == actionName); Verify.That(actions.Any(), "Action name '{0}' isn't recognized", actionName); _routeToRender = "~/{0}/{1}".FormatWith(_controllerDescriptor.ControllerName, actionName); }
public void UpdateActionList() { DB.ControllerActions.ToList(); List <Type> typeList = Assembly.GetExecutingAssembly().GetExportedTypes().Where(r => r.HasBaseType(typeof(Controller))).ToList(); //Delete non-existing controllers foreach (var item in typeList) { ReflectedControllerDescriptor controllerDes = new ReflectedControllerDescriptor(item); string controllerName = controllerDes.ControllerName; ControllerAction controllerOfActionAuthorization = DB.ControllerActions.Where(r => r.Controller == controllerName && string.IsNullOrEmpty(r.Action) && string.IsNullOrEmpty(r.HttpVerb) ).FirstOrDefault(); if (controllerOfActionAuthorization == null) { controllerOfActionAuthorization = new ControllerAction(); controllerOfActionAuthorization.Controller = controllerName; DB.AddToControllerActions(controllerOfActionAuthorization); Save(); } List <ActionDescriptor> actionDescriptorList = controllerDes.GetCanonicalActions().ToList(); foreach (var actionDesc in actionDescriptorList) { string parameters = string.Join(", ", actionDesc.GetParameters().Select(r => r.ParameterName)); string httpVerb = actionDesc.GetHttpVerb(); string actionName = actionDesc.ActionName; ControllerAction actionOfActionAuthorization = DB.ControllerActions.Where(r => r.Controller == controllerName && r.Action == actionName && r.HttpVerb == httpVerb).FirstOrDefault(); if (actionOfActionAuthorization == null) { actionOfActionAuthorization = new ControllerAction(); actionOfActionAuthorization.Controller = controllerName; actionOfActionAuthorization.Action = actionName; actionOfActionAuthorization.Parameters = parameters; actionOfActionAuthorization.HttpVerb = httpVerb; DB.AddToControllerActions(actionOfActionAuthorization); Save(); } } } }
protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName) { var reflectedControllerDescriptor = new ReflectedControllerDescriptor(controllerDescriptor.ControllerType); var actions = reflectedControllerDescriptor.GetCanonicalActions(); foreach (var action in actions) { if (action.ActionName == actionName) { return(action); } } return(controllerDescriptor.FindAction(controllerContext, actionName)); }
private void ListValidActions(RequestContext requestContext) { ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController)); ActionDescriptor[] actionDescriptors = controllerDescriptor.GetCanonicalActions(); if (actionDescriptors.Any()) { foreach (ActionDescriptor actionDescriptor in actionDescriptors) { requestContext.HttpContext.Response.Write(actionDescriptor.ActionName + "<br/>"); } } else { requestContext.HttpContext.Response.Write("无合法的Action方法"); } }
public static HelperResult DocumentationLink <T>(this HtmlHelper <T> htmlHelper, string label) { DocumentationAttribute attribute = null; var viewContext = htmlHelper.ViewContext; var controllerDescriptor = new ReflectedControllerDescriptor(viewContext.Controller.GetType()); var actionName = viewContext.RouteData.Values["action"] as string; var actionDescriptor = controllerDescriptor .GetCanonicalActions() .Where(x => String.Equals(x.ActionName, actionName, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (actionDescriptor != null) { attribute = actionDescriptor .GetCustomAttributes(typeof(DocumentationAttribute), true) .Cast <DocumentationAttribute>() .FirstOrDefault(); } if (attribute == null) { attribute = controllerDescriptor .GetCustomAttributes(typeof(DocumentationAttribute), true) .Cast <DocumentationAttribute>() .FirstOrDefault(); } var link = attribute == null ? BaseUrl : string.Format("{0}{1}", BaseUrl, attribute.DocumentPath); return(new HelperResult(writer => { var builder = new TagBuilder("a"); builder.MergeAttribute("href", link); builder.MergeAttribute("target", "_blank"); writer.Write(builder.ToString(TagRenderMode.StartTag)); writer.Write(label); writer.Write(builder.ToString(TagRenderMode.EndTag)); })); }
private IEnumerable <MyAction> GetListOfAction(Type controller) { var navItems = new List <MyAction>(); // Get a descriptor of this controller var controllerDesc = new ReflectedControllerDescriptor(controller); // Look at each action in the controller foreach (ActionDescriptor action in controllerDesc.GetCanonicalActions()) { bool validAction = true; bool isHttpPost = false; // Get any attributes (filters) on the action object[] attributes = action.GetCustomAttributes(false); // Look at each attribute foreach (object filter in attributes) { // Can we navigate to the action? if (filter is ChildActionOnlyAttribute) { validAction = false; break; } if (filter is HttpPostAttribute) { isHttpPost = true; } } // Add the action to the list if it's "valid" if (validAction) { navItems.Add(new MyAction() { Name = action.ActionName, IsHttpPost = isHttpPost }); } } return(navItems); }
//FROM: http://stackoverflow.com/questions/2721869/security-aware-action-link public static bool CheckHasActionPermission(ViewContext viewContext, string actionName, string controllerName = null, bool useNamespaceFallback = false) { //if the controller name is empty the ASP.NET convention is: //"we are linking to a different controller ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName) ? viewContext.Controller : GetControllerByName(viewContext, controllerName, useNamespaceFallback); var controllerContext = new ControllerContext(viewContext.RequestContext, controllerToLinkTo); var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType()); var actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(x => String.Equals(x.ActionName, actionName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); //Originally it was: //var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); //I changed it because, I want to check accessibility to an POST action. Maybe it could fail for actions for different http method and the same name return(ActionIsAuthorized(controllerContext, actionDescriptor)); }
public static bool HasActionPermission(string actionName, string controllerName, ControllerContext currentControlerContext) { HtmlHelper htmlHelper = new HtmlHelper(new ViewContext(currentControlerContext, new WebFormView(currentControlerContext, "omg"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage()); //if the controller name is empty the ASP.NET convention is: //"we are linking to a different controller ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName) ? htmlHelper.ViewContext.Controller : GetControllerByName(htmlHelper, controllerName); var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo); var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType()); var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); if (actionDescriptor == null) { actionDescriptor = controllerDescriptor.GetCanonicalActions().FirstOrDefault(a => a.ActionName == actionName); } return(ActionIsAuthorized(controllerContext, actionDescriptor)); }
public static bool HasRightsToAction(this Type controllerType, string actionName) { var controllerDescriptor = new ReflectedControllerDescriptor(controllerType); if (controllerDescriptor == null) { throw new ArgumentException("Invalid controller type!"); } var actionDescriptor = controllerDescriptor.GetCanonicalActions() .FirstOrDefault(item => item.ActionName == actionName); if (actionDescriptor?.GetCustomAttributes(typeof(CustomAuthorizeAttribute), false).FirstOrDefault() is CustomAuthorizeAttribute attribute && !attribute.HasRightsToAction(actionDescriptor)) { return(false); } attribute = controllerDescriptor.GetCustomAttributes(typeof(CustomAuthorizeAttribute), false) .FirstOrDefault() as CustomAuthorizeAttribute ?? new CustomAuthorizeAttribute(); return(attribute.HasRightsToAction(actionDescriptor)); }
public void OnActionExecuted(ActionExecutedContext filterContext) { ViewResult viewResult = filterContext.Result as ViewResult; if (viewResult != null && viewResult.Model != null) { IAdminModel model = viewResult.Model as IAdminModel; if (model == null) { throw new InvalidOperationException(string.Format("Model ({0}) does not implement IAdminModel", viewResult.GetType().Name)); } model.Notifications = App.Instance.Notifications.Get(filterContext.HttpContext.User); // this was populated by the AddInControllerFactory IControllerMetadata metadata = (IControllerMetadata) filterContext.RequestContext.HttpContext.Items[AddInControllerFactory.MetadataKey]; string actionText = string.Empty; // TODO FIX THIS SOMEHOW, this is pretty crappy var allControllerExports = App.Instance.Container.GetExports( new ContractBasedImportDefinition( ContractNames.AdminController, AttributedModelServices.GetTypeIdentity(typeof(IController)), Enumerable.Empty <KeyValuePair <string, Type> >(), ImportCardinality.ZeroOrMore, false, false, CreationPolicy.NonShared)); List <Navigation> menu = new List <Navigation>(); foreach (Export export in allControllerExports) { IControllerMetadata controllerMetadata = AttributedModelServices.GetMetadataView <IControllerMetadata>(export.Metadata); ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(export.Value.GetType()); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) { continue; } UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext); Uri defaultTargetUrl = null; List <Navigation> children = new List <Navigation>(); foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) { continue; } // TODO replace anon class with concrete type? string targetUrl = urlHelper.Action(actionAttr.Name, controllerAttr.Name, new { packageId = controllerMetadata.PackageId, packageVersion = controllerMetadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) { defaultTargetUrl = target; } bool isActive = filterContext.ActionDescriptor.ActionName == actionDescriptor.ActionName && filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == descriptor.ControllerType; if (isActive) { actionText = actionAttr.Text; } Navigation navigation = new Navigation(null, actionAttr.Order, actionAttr.Text, target, isActive, Enumerable.Empty <Navigation>()); children.Add(navigation); } bool isAnyChildActive = children.Any(n => n.IsActive); // if there's only one child, ignore it if (children.Count == 1) { children.Clear(); } menu.Add(new Navigation(controllerAttr.Group, controllerAttr.Order, controllerAttr.Text, defaultTargetUrl, isAnyChildActive, children)); } model.Navigation = menu.OrderBy(n => n.Order).ToArray(); model.PageTitle = "LostDoc Administration " + metadata.Text; if (!string.IsNullOrWhiteSpace(actionText)) { model.PageTitle += string.Format(" - {0}", actionText); } } }
public ActionResult Index() { ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(typeof(HomeController)); return(View(controllerDescriptor.GetCanonicalActions())); }