public void FindActionThrowsIfActionNameIsNull() { // Arrange Type controllerType = typeof(MyController); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType); // Act & assert Assert.ThrowsArgumentNullOrEmpty( delegate { cd.FindAction(new Mock <ControllerContext>().Object, null); }, "actionName" ); }
public void GetCustomAttributesWithAttributeTypeCallsTypeGetCustomAttributes() { // Arrange object[] expected = new object[0]; Mock <Type> mockType = new Mock <Type>(); mockType.Setup(t => t.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(mockType.Object); // Act object[] returned = cd.GetCustomAttributes(typeof(ObsoleteAttribute), true); // Assert Assert.Same(expected, returned); }
public void FindActionThrowsIfControllerContextIsNull() { // Arrange Type controllerType = typeof(MyController); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType); // Act & assert Assert.ThrowsArgumentNull( delegate { cd.FindAction(null, "someName"); }, "controllerContext" ); }
private DefaultContractResolver GetExecutingControllerSerializer() { var controllerDescriptor = new ReflectedControllerDescriptor(ControllerContext.Controller.GetType()); var action = RouteData.GetRequiredString("action"); var actionDescriptor = controllerDescriptor.FindAction(ControllerContext, action); Attributes.SerializerAttribute attribute = (Attributes.SerializerAttribute) (actionDescriptor.GetCustomAttributes(typeof(Attributes.SerializerAttribute), true).FirstOrDefault() ?? controllerDescriptor.GetCustomAttributes(typeof(Attributes.SerializerAttribute), true).FirstOrDefault()); if (attribute != null) { return(CacheHelper.GetFromCacheOrDefault <DefaultContractResolver>(HttpContext, attribute.Serializer)); } return(null); }
protected override void ExecuteCore() { Type controllerType = this.ControllerContext.Controller.GetType(); ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType); if (controllerDescriptor.IsDefined(typeof(SpecialSetUpAttribute), true)) { //Do special setup } else { //Do normal setup } base.ExecuteCore(); }
public IEnumerable <Attribute> GetAttributes( string actionName, string controllerName, string method = "GET") { var controllerFactory = ControllerBuilder.Current.GetControllerFactory(); var otherController = (ControllerBase)controllerFactory.CreateController(new RequestContext(_htmlHelper.ViewContext.HttpContext, new RouteData()), controllerName); var controllerDescriptor = new ReflectedControllerDescriptor(otherController.GetType()); var controllerContext2 = new ControllerContext(new HttpContextWrapperWithHttpMethod(_htmlHelper.ViewContext.HttpContext.ApplicationInstance.Context, method), new RouteData(), otherController); var actionDescriptor = controllerDescriptor.FindAction(controllerContext2, actionName); var attributes = actionDescriptor.GetCustomAttributes(true).Cast <Attribute>().ToArray(); return(attributes); }
public static T Invoke <T>(Expression <Func <T> > exp) where T : ActionResult { var methodCall = (MethodCallExpression)exp.Body; var method = methodCall.Method; var memberExpression = (MemberExpression)methodCall.Object; var getCallerExpression = Expression.Lambda <Func <Object> >(memberExpression); var getCaller = getCallerExpression.Compile(); var ctrlr = (Controller)getCaller(); ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(ctrlr.GetType()); ActionDescriptor actionDescriptor = new ReflectedActionDescriptor(method, method.Name, controllerDescriptor); // OnActionExecuting var rc = new RequestContext(); ctrlr.ControllerContext = new ControllerContext(rc, ctrlr); var ctx1 = new ActionExecutingContext(ctrlr.ControllerContext, actionDescriptor, new Dictionary <string, object>()); var onActionExecuting = ctrlr.GetType() .GetMethod("OnActionExecuting", BindingFlags.Instance | BindingFlags.NonPublic); onActionExecuting.Invoke(ctrlr, new object[] { ctx1 }); // call controller method var result = exp.Compile()(); // OnActionExecuted var ctx2 = new ActionExecutedContext(ctrlr.ControllerContext, actionDescriptor, false, null) { Result = result }; var onActionExecuted = ctrlr.GetType() .GetMethod("OnActionExecuted", BindingFlags.Instance | BindingFlags.NonPublic); onActionExecuted.Invoke(ctrlr, new object[] { ctx2 }); return((T)ctx2.Result); }
/// <summary> /// Gets the action list. /// </summary> /// <param name="controllerType">Type of the controller.</param> /// <returns>IEnumerable<ActionDescription>.</returns> private static IEnumerable <ActionDescription> GetActionList(Type controllerType) { var actions = new ReflectedControllerDescriptor(controllerType).GetCanonicalActions().ToList(); var actionList = (from actionDescriptor in actions let attribute = actionDescriptor.GetCustomAttributes(typeof(DescriptionAttribute), false).LastOrDefault() as DescriptionAttribute let acnDescription = attribute == null ? "" : attribute.Description select new ActionDescription { Name = actionDescriptor.ActionName, Description = acnDescription }).ToList(); actionList = actionList.GroupBy(a => a.Name).Select(g => g.First()).ToList(); return(actionList); }
public static bool HasActionPermission(this HtmlHelper htmlHelper, string actionName, string controllerName) { //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); return(ActionIsAuthorized(controllerContext, actionDescriptor)); }
public void FindActionReturnsActionDescriptorIfFound() { // Arrange Type controllerType = typeof(MyController); MethodInfo targetMethod = controllerType.GetMethod("AliasedMethod"); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType); // Act ActionDescriptor ad = cd.FindAction(new Mock <ControllerContext>().Object, "NewName"); // Assert Assert.AreEqual("NewName", ad.ActionName); Assert.IsInstanceOfType(ad, typeof(ReflectedActionDescriptor)); Assert.AreSame(targetMethod, ((ReflectedActionDescriptor)ad).MethodInfo, "MethodInfo pointed to wrong method."); Assert.AreSame(cd, ad.ControllerDescriptor, "Controller did not point back to correct descriptor."); }
public void FindActionReturnsActionDescriptorIfFound() { // Arrange Type controllerType = typeof(MyController); MethodInfo targetMethod = controllerType.GetMethod("AliasedMethod"); ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType); // Act ActionDescriptor ad = cd.FindAction(new ControllerContext(), "NewName"); // Assert Assert.Equal("NewName", ad.ActionName); Assert.IsType <ReflectedActionDescriptor>(ad); Assert.Same(targetMethod, ((ReflectedActionDescriptor)ad).MethodInfo); Assert.Same(cd, ad.ControllerDescriptor); }
public void GetFilters_IncludesTypeAttributesFromDerivedTypeWhenMethodIsOnBaseClass() { // DDB #208062 // Arrange var context = new ControllerContext { Controller = new DerivedController() }; var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType()); var action = context.Controller.GetType().GetMethod("MyActionMethod"); var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor); var provider = new FilterAttributeFilterProvider(); // Act IEnumerable <Filter> filters = provider.GetFilters(context, actionDescriptor); // Assert Assert.NotNull(filters.Select(f => f.Instance).Cast <MyFilterAttribute>().Single()); }
/// <summary> /// /// </summary> /// <param name="action"></param> /// <returns>arr[0] controllerName, arr[1] actionName</returns> public static string[] GetControllerNameAndActionName(Expression <Func <T, ActionResult> > action) { string[] arr = new string[2]; ReflectedControllerDescriptor controllerDes = new ReflectedControllerDescriptor(typeof(T)); arr[0] = controllerDes.ControllerName; MethodCallExpression methodExp = action.Body as MethodCallExpression; if (methodExp != null) { arr[1] = methodExp.Method.Name; } return(arr); }
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 void GetFilters_IncludesAttributesOnActionMethod() { // Arrange var context = new ControllerContext { Controller = new ControllerWithActionAttribute() }; var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType()); var action = context.Controller.GetType().GetMethod("MyActionMethod"); var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor); var provider = new FilterAttributeFilterProvider(); // Act Filter filter = provider.GetFilters(context, actionDescriptor).Single(); // Assert MyFilterAttribute attrib = filter.Instance as MyFilterAttribute; Assert.IsNotNull(attrib); Assert.AreEqual(FilterScope.Action, filter.Scope); Assert.AreEqual(1234, filter.Order); }
public JsonResult GetActionInController(string controllerName) { try { controllerName = controllerName + "Controller"; List <string> listAction = new List <string>(); var types = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where typeof(IController).IsAssignableFrom(t) && string.Equals(controllerName, t.Name, StringComparison.OrdinalIgnoreCase) select t; var controllerType = types.FirstOrDefault(); if (controllerType != null) { listAction = new ReflectedControllerDescriptor(controllerType).GetCanonicalActions().Select(x => x.ActionName).Distinct().ToList(); } var jsonResults = new { data = listAction }; return(Json(jsonResults, JsonRequestBehavior.AllowGet)); //The code that causes the error goes here. } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); FileNotFoundException exFileNotFound = exSub as FileNotFoundException; if (exFileNotFound != null) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } string errorMessage = sb.ToString(); //Display or log the error based on your application. return(Json(new { data = new List <string>() }, JsonRequestBehavior.AllowGet)); } }
public void SelectBestCandidate_SelectByActionNameSelector_RouteProvidesName() { // Arrange Type controllerType = typeof(TestController); ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor( controllerType ); RouteData routeData = new RouteData(); routeData.Values["action"] = "Action1"; DirectRouteCandidate better = new DirectRouteCandidate() { ActionDescriptor = ActionDescriptorFrom <TestController>(c => c.Action2()), ActionNameSelectors = new ActionNameSelector[] { (context, name) => name == "Action1" }, ControllerDescriptor = controllerDescriptor, RouteData = routeData, }; DirectRouteCandidate worse = new DirectRouteCandidate() { ActionDescriptor = ActionDescriptorFrom <TestController>(c => c.Action2()), ControllerDescriptor = controllerDescriptor, RouteData = routeData, }; List <DirectRouteCandidate> candidates = new List <DirectRouteCandidate>() { better, worse, }; // Act DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate( candidates, new ControllerContext() ); // Assert Assert.Same(better, actual); }
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); } //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))); } } } }
public void SelectBestCandidate_ChoosesByPrecedence_WithActionSelectors() { // Arrange Type controllerType = typeof(TestController); ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor( controllerType ); DirectRouteCandidate better = new DirectRouteCandidate() { ActionDescriptor = ActionDescriptorFrom <TestController>(c => c.Action1()), ActionSelectors = new ActionSelector[] { (context) => true }, ControllerDescriptor = controllerDescriptor, Order = 0, Precedence = 1, RouteData = new RouteData(), }; DirectRouteCandidate worse = new DirectRouteCandidate() { ActionDescriptor = ActionDescriptorFrom <TestController>(c => c.Action1()), ActionSelectors = new ActionSelector[] { (context) => true }, ControllerDescriptor = controllerDescriptor, Order = 0, Precedence = 2, RouteData = new RouteData(), }; List <DirectRouteCandidate> candidates = new List <DirectRouteCandidate>() { better, worse, }; // Act DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate( candidates, new ControllerContext() ); // Assert Assert.Same(better, actual); }
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); }
private ActionResult Run(string controllerName, string actionName, Dictionary <string, object> parameters) { // get the controller var ctrlFactory = ControllerBuilder.Current.GetControllerFactory(); var ctrl = ctrlFactory.CreateController(this.Request.RequestContext, controllerName) as Controller; var ctrlContext = new ControllerContext(this.Request.RequestContext, ctrl); var ctrlDesc = new ReflectedControllerDescriptor(ctrl.GetType()); // get the action var actionDesc = ctrlDesc.FindAction(ctrlContext, actionName); // Change the route data so the good default view will be called in time foreach (var parameter in parameters) { if (!ctrlContext.RouteData.Values.ContainsKey(parameter.Key)) { ctrlContext.RouteData.Values.Add(parameter.Key, parameter.Value); } } ctrlContext.RouteData.Values["controller"] = controllerName; ctrlContext.RouteData.Values["action"] = actionName; // To call the action in the controller, the parameter dictionary needs to have a value for each parameter, even the one with a default var actionParameters = actionDesc.GetParameters(); foreach (var actionParameter in actionParameters) { if (parameters.ContainsKey(actionParameter.ParameterName)) /* If we already have a value for the parameter, change it's type */ { parameters[actionParameter.ParameterName] = Convert.ChangeType(parameters[actionParameter.ParameterName], actionParameter.ParameterType); } else if (actionParameter.DefaultValue != null) /* If we have no value for it but it has a default value, use it */ { parameters[actionParameter.ParameterName] = actionParameter.DefaultValue; } else /* Parameter missing to call the action! */ { return(HttpNotFound()); } } // Set culture on the thread (Because my BaseController.BeginExecuteCore won't be called) CultureHelper.SetImplementedCulture(); // Return the other action result as the current action result return(actionDesc.Execute(ctrlContext, parameters) as ActionResult); }
public static ActionResult Run(this Controller helper, string moduleId, string controllerName, string actionName, RouteValueDictionary routeValues = null) { if (!isModuleCallValid(moduleId) || !isActionCallValid(moduleId, controllerName, actionName, false)) { return(new HttpStatusCodeResult(HttpStatusCode.NotAcceptable, "Not Acceptable.")); //throw new InvalidOperationException("Bad Request"); } controllerName = controllerName + "Controller"; Type controllerType = ModuleManager.GetModuleInfo(moduleId).Plugin.GetType().Assembly .GetTypes().Where(p => p.Name.Equals(controllerName)).First(); if (!ControllerBuilder.Current.DefaultNamespaces.Contains(controllerType.Namespace)) { ControllerBuilder.Current.DefaultNamespaces.Add(controllerType.Namespace); } try { Controller ctrl = DependencyResolver.Current.GetService(controllerType) as Controller; var ctrlContext = new ControllerContext(helper.Request.RequestContext, ctrl); ctrl.ControllerContext = ctrlContext; var ctrlDesc = new ReflectedControllerDescriptor(ctrl.GetType()); // get the action descriptor var actionDesc = ctrlDesc.FindAction(ctrlContext, actionName); try { // execute var result = actionDesc.Execute(ctrlContext, routeValues) as ActionResult; return(result); } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, String.Format("Action failed to execute. Reason: {0}", ex.Message))); } } catch (Exception ex) { return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable, String.Format("Service Unavailable. Reason: {0}", ex.Message))); } }
//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 void SelectBestCandidate_ExcludesFailedActionSelectors_NoneValid() { // Arrange Type controllerType = typeof(TestController); ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor( controllerType ); DirectRouteCandidate better = new DirectRouteCandidate() { ActionDescriptor = ActionDescriptorFrom <TestController>(c => c.Action1()), ActionSelectors = new ActionSelector[] { (context) => false, }, ControllerDescriptor = controllerDescriptor, Order = 0, RouteData = new RouteData(), }; DirectRouteCandidate worse = new DirectRouteCandidate() { ActionDescriptor = ActionDescriptorFrom <TestController>(c => c.Action1()), ActionSelectors = new ActionSelector[] { (context) => false, }, ControllerDescriptor = controllerDescriptor, Order = 1, RouteData = new RouteData(), }; List <DirectRouteCandidate> candidates = new List <DirectRouteCandidate>() { better, worse, }; // Act DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate( candidates, new ControllerContext() ); // Assert Assert.Null(actual); }
/// <summary> /// Runs all authorization filters just like MVC does. /// </summary> /// <param name="controller"></param> /// <param name="actionName"></param> /// <param name="httpMethod"></param> /// <returns></returns> public static ActionResult RunOnAuthorization(Controller controller, string actionName = null, string httpMethod = null) { // reference: http://haacked.com/archive/2008/08/13/aspnetmvc-filters.aspx // reference: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs // Filter execution order: Authorization, Action Execution, Result Execution, Exception Handling httpMethod = httpMethod ?? controller.ControllerContext.HttpContext.Request.HttpMethod ?? "GET"; actionName = actionName ?? controller.ControllerContext.RouteData.GetRequiredString("action"); if (string.IsNullOrEmpty(actionName)) { throw new Exception("actionName is null or empty"); } var controllerContextWithMethodParam = new ControllerContext( new MvcHelper.MockHttpContext { Request2 = new MvcHelper.MockHttpRequest { HttpMethod2 = httpMethod } }, new RouteData(), controller); var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); var actionDescriptor = controllerDescriptor.FindAction(controllerContextWithMethodParam, actionName); var authorizationContext = new AuthorizationContext(controller.ControllerContext, actionDescriptor); var filters = GetFilters <IAuthorizationFilter>(controller, actionDescriptor, actionName, httpMethod); foreach (var eachFilter in filters) { eachFilter.OnAuthorization(authorizationContext); if (authorizationContext.Result != null) { return(authorizationContext.Result); } } return(null); }
public static bool CheckAccess(RequestContext requestContext) { var routeData = requestContext.RouteData; var controllerName = routeData.Values["controller"] as string; var actionName = routeData.Values["action"] as string; var controller = GetControllerByName(requestContext, controllerName); var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); var controllerContext = new ControllerContext(requestContext, controller); var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); var resourceClaims = actionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(ClaimsAuthorizeAttribute), false) .Cast <ClaimsAuthorizeAttribute>() .SelectMany(auth => auth.GetClaims()).ToList(); resourceClaims.AddRange(actionDescriptor.GetCustomAttributes(typeof(ClaimsAuthorizeAttribute), false).Cast <ClaimsAuthorizeAttribute>() .SelectMany(c => c.GetClaims())); var hasAccess = ClaimsAuthorization.CheckAccess(actionName, resourceClaims.ToArray()); return(hasAccess); }
public void GetFilters_IncludesAttributesOnActionMethod() { // Arrange var context = new ControllerContext { Controller = new ControllerWithActionAttribute() }; var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType()); var action = context.Controller.GetType().GetMethod("MyActionMethod"); var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor); var provider = new FilterAttributeFilterProvider(); // Act Filter filter = provider.GetFilters(context, actionDescriptor).Single(); // Assert MyFilterAttribute attrib = filter.Instance as MyFilterAttribute; Assert.NotNull(attrib); Assert.Equal(FilterScope.Action, filter.Scope); Assert.Equal(1234, filter.Order); }
protected override void ExecuteCore() { Type controllerType = this.ControllerContext.Controller.GetType(); ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType); // Edit start string actionName = Convert.ToString(this.ControllerContext.RouteData.Values["action"]); string controller = Convert.ToString(this.ControllerContext.RouteData.Values["controller"]); // Edit end if (controllerDescriptor.IsDefined(typeof(SpecialSetUpAttribute), true)) { //Do special setup } else { //Do normal setup } base.ExecuteCore(); }
public JsonResult GetActionInController(string controllerName) { controllerName = controllerName + "Controller"; List <string> listAction = new List <string>(); var types = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where typeof(IController).IsAssignableFrom(t) && string.Equals(controllerName, t.Name, StringComparison.OrdinalIgnoreCase) select t; var controllerType = types.FirstOrDefault(); if (controllerType != null) { listAction = new ReflectedControllerDescriptor(controllerType).GetCanonicalActions().Select(x => x.ActionName).Distinct().ToList(); } var jsonResults = new { data = listAction }; return(Json(jsonResults, JsonRequestBehavior.AllowGet)); }
public void Test_Ninject_should_inject_for_Action_Attributes() { // Arrange var context = new ControllerContext { Controller = new ControllerWithActionAttribute() }; var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType()); var action = context.Controller.GetType().GetMethod("ActionMethod"); var actionDescriptor = new ReflectedActionDescriptor(action, "ActionMethod", controllerDescriptor); var mockKernel = new Mock <IKernel>(); mockKernel.Setup(k => k.Inject(It.IsAny <MyFilterAttribute>())).Verifiable(); var provider = new NinjectFilterAttributeFilterProvider(mockKernel.Object); // act provider.GetFilters(context, actionDescriptor); // assert mockKernel.Verify(); }
public void GetFilters_IncludesTypeAttributesFromDerivedTypeWhenMethodIsOnBaseClass() { // DDB #208062 // Arrange var context = new ControllerContext { Controller = new DerivedController() }; var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType()); var action = context.Controller.GetType().GetMethod("MyActionMethod"); var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor); var provider = new FilterAttributeFilterProvider(); // Act IEnumerable<Filter> filters = provider.GetFilters(context, actionDescriptor); // Assert Assert.NotNull(filters.Select(f => f.Instance).Cast<MyFilterAttribute>().Single()); }