2016-08-11 3 views
7

일반 조치 필터가 있으며 OnActionExecuting 방법으로 현재 모델을 가져오고 싶습니다. 현재 구현은 다음과 같습니다.조치 필터에서 현재 모델을 얻는 방법

public class CommandFilter<T> : IActionFilter where T : class, new() 
{ 
     public void OnActionExecuting(ActionExecutingContext actionContext) 
     { 
      var model= (T)actionContext.ActionArguments["model"]; 
     } 
} 

내 모든 모델 이름이 동일하면 잘 작동합니다. 하지만 differnet 모델 이름을 사용하고 싶습니다.

이 문제를 해결하는 방법은 무엇입니까?

당신은 모델에 접근 할 수 base MVC ControllerActionExecutingContext.Controller 재산

/// <summary> 
    /// Gets the controller instance containing the action. 
    /// </summary> 
    public virtual object Controller { get; } 

및 변환 결과를 사용할 수 있습니다

public class HomeController : Controller 
{ 
    [ServiceFilter(typeof(CommandActionFilter<CreateInput>))] 
    public IActionResult Create([FromBody]CreateInput model) 
    { 
     return new OkResult(); 
    } 
} 
+0

같은 http://stackoverflow.com/questions/872796/asp-net-mvc-accessing-view-model-from-a-custom을 쓸 수 있습니다 경우 -action-filter – user2184057

+0

@ user2184057 이것은보기 모델 용이며 요청 모델 – Set

답변

4

ActionExecutingContext.ActionArguments 단지입니다

/// <summary> 
    /// Gets the arguments to pass when invoking the action. Keys are parameter names. 
    /// </summary> 
    public virtual IDictionary<string, object> ActionArguments { get; } 

및 하드 코드 된 매개 변수 이름 ("모델")을 피하기 위해 루프해야합니다. asp.net에 대한 the same SO answer에서 우리는 몇 가지 특정 요구 사항에 대한 유사한 객체의 클래스에 작업을 필요로하는 일반적인 액션 필터를 만들 때

, 우리는 우리의 모델은이 => 아는 인터페이스가있는 주장이다 구현 할 수 우리가 작업 할 필요가있는 모델이며 인터페이스를 통해 메소드를 호출 할 수 있습니다.

당신은 당신이

public void OnActionExecuting(ActionExecutingContext actionContext) 
{ 
    foreach(var argument in actionContext.ActionArguments.Values.Where(v => v is T))) 
    { 
     T model = argument as T; 
     // your logic 
    } 
} 
+0

"T는"다음 "T는"어떤 식 으로든 그 코드를 개선하기 위해 무엇입니까? 당신은 내 관점에서 두 번 캐스팅하고 있습니다 .... –

4

편집 :

((Controller)actionExecutingContext.Controller).ViewData.Model 
+0

이 아니라 캐스트 예외가 발생합니다. 'MyNamespace.HomeController'유형의 객체를 'Microsoft.AspNetCore.Mvc.Controller'유형으로 캐스팅 할 수 없습니다. –

+0

HomeController의 정의를 보여줄 수 있습니까? – Set

+0

죄송합니다. 컨트롤러 기본 설정을 잊어 버렸습니다. 내가 코드를 편집했지만 지금은 모델이 null입니다 (어쩌면 내가 아무것도 그리워). 내 업데이 트를 참조하십시오. 지금은 –

관련 문제