2016-10-11 9 views
1

.NET 4.5では、RouteData.ValuesのRouteValueDictionaryに何かを追加した場合、これをコントローラのインパラメータとして追加することでコントローラで解決できます.NETコアでは動作しないようです。RouteData.Valuesパラメータを.NETコアのコントローラパラメータにマップする

これは私のiRouterののRouteAsync方法であって、この後

public async Task RouteAsync(RouteContext context) 
{ 
    if (context == null) throw new ArgumentNullException(nameof(context)); 

    var model = GetMyModel(); 
    if (model == null) 
    { 
     await _target.RouteAsync(context); 
     return; 
    } 
    context.RouteData.Values["mymodel"] = model; 
    var routeValues = new RouteValueDictionary 
    { 
     {"controller", pageController.Name.Replace("Controller", string.Empty)}, 
     {"action", "Index"}, 
     {"mymodel", model } 
    }; 

    var tokenValues = new RouteValueDictionary 
    { 
     {"mymodel", model } 
    }; 
    // Set our values to the route data. 
    // Don't do it when creating the snapshot as we'd like them to be there after the restore as well. 
    foreach (var tokenValueKey in tokenValues.Keys) 
    { 
     context.RouteData.DataTokens[tokenValueKey] = tokenValues[tokenValueKey]; 
    } 
    foreach (var routeValueKey in routeValues.Keys) 
    { 
     context.RouteData.Values[routeValueKey] = routeValues[routeValueKey]; 
    } 

    // This takes a snapshot of the route data before it is routed again 
    var routeDataSnapshot = context.RouteData.PushState(_target, routeValues, tokenValues); 

    try 
    { 
     await _target.RouteAsync(context); 
    } 
    finally 
    { 
     // Restore snapshot 
     routeDataSnapshot.Restore(); 
    } 
} 

、私のコントローラは、実際に呼ばれているが、パラメータに、mymodelは、単にデフォルト値ではなく、私は、ルータに設定された値です。 RouteData.Valuesを見ると、キー「mymodel」があり、値を持っています。パラメータがin-parameterに設定されていないのはなぜですか?モデルのバインドにミドルウェアを追加する必要がありますか?

public IActionResult Index(MyModelClass mymodel) 
{ 
    return View(); 
} 

答えて

1

RouteDataは、プロパティとしてコントローラインスタンスからアクセスできます。

public class SomeControllerController : Controller { 
    public IActionResult Index() { 
     if (base.RouteData.Values.ContainsKey("mymodel") == false) { 
      return NotFound(); 
     } 
     MyModel model = (MyModel) base.RouteData.Values["mymodel"]; 
     //LOGIC... 
     return Index(model); 
    } 
} 

クリーナーimlementationのために、あなたはこれを行うには、抽象コントローラを作成することができます。

ref:https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.routedata(v=vs.118).aspx

関連する問題