将RouteData.Values参数映射到.NET Core中的控制器参数

时间:2016-10-11 15:16:44

标签: c# asp.net-core asp.net-mvc-routing asp.net-core-mvc

在.NET 4.5中,如果我在RouteData.Values中向RouteValueDictionary添加了任何东西,我可以在控制器中通过将其添加为控制器的in-parameter来解决这个问题,但这似乎不适用于.NET Core

这是我的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也没有设置为this?我是否需要为模型绑定添加一些中间件?

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

1 个答案:

答案 0 :(得分: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);
    }
}

为了更清洁,您可以创建一个抽象控制器来执行此操作。

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