2009-10-28 3 views
3

컨트롤러에서 asp.net MVC의 모든 작업 이름을 가져 오는 코드를 작성하려면 어떻게해야합니까?컨트롤러에서 모든 작업 이름을 얻는 방법

컨트롤러의 모든 동작 이름을 자동으로 표시하려고합니다.

누구든지이 작업을 수행하는 방법을 알고 있습니까?

감사합니다.

답변

3

ActionNameSelectorAttribute에서 파생 된 사용자 지정 특성을 작성하고 을 임의의 사용자 지정 코드 (임의의 GUID와 이름을 비교하는 코드 포함)로 덮어 쓰기 때문에이 일반적인 해결책은 없습니다. 이 경우 속성에서 허용 할 작업 이름을 알 수있는 방법이 없습니다.

그들이 ActionNameAttributeName 속성을 가지고 있는지 당신은 단지 메소드 이름 또는 내장 ActionNameAttribute은 다음 클래스를 통해 반영 할 수는 ActionResult을 반환 public 메소드의 모든 이름을 얻고 확인을 고려에 솔루션을 제한하는 경우 메서드 이름을 재정의합니다. 당신은 당신의 필요에 따라 더 많은 일을해야합니다

Type t = typeof(YourControllerType); 
MethodInfo[] mi = t.GetMethods(); 
foreach (MethodInfo m in mi) 
{ 
    if (m.IsPublic) 
     if (typeof(ActionResult).IsAssignableFrom(m.ReturnParameter.ParameterType)) 
      methods = m.Name + Environment.NewLine + methods; 
} 

:와

+0

간단한 예를 들어 주시겠습니까? –

0

리플렉션을 사용하면 시작할 수있는 아주 좋은 장소입니다.

2

당신은 시작할 수 있습니다.

+0

예를 들어 주셔서 감사합니다. 매우 도움이됩니다. –

8

저는이 질문에 대해 지금 당분간 씨름 해 왔으며 대부분의 시간 동안 해결해야 할 해결책을 찾았다 고 생각합니다. 문제의 컨트롤러에 대해 ControllerDescriptor을 가져온 다음 ActionDescriptor을 확인하고 ControllerDescriptor.GetCanonicalActions()을 반환합니다.

내 컨트롤러에서 부분 뷰를 반환하는 작업이 끝났지 만 어떤 일이 일어나고 있는지 파악하기가 쉽습니다. 따라서 코드를 자유롭게 사용하고 필요에 맞게 변경할 수 있습니다.

[ChildActionOnly] 
public ActionResult Navigation() 
{ 
    // List of links 
    List<string> NavItems = new List<string>(); 

    // Get a descriptor of this controller 
    ReflectedControllerDescriptor controllerDesc = new ReflectedControllerDescriptor(this.GetType()); 

    // Look at each action in the controller 
    foreach (ActionDescriptor action in controllerDesc.GetCanonicalActions()) 
    { 
     bool validAction = true; 

     // 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 HttpPostAttribute || filter is ChildActionOnlyAttribute) 
      { 
       validAction = false; 
       break; 
      } 
     } 

     // Add the action to the list if it's "valid" 
     if (validAction) 
      NavItems.Add(action.ActionName); 
    } 

    return PartialView(NavItems); 
} 

아마도 더 많은 필터가 필요 하겠지만, 지금은 내 필요에 맞는 것입니다.

관련 문제