如何将参数传递给控制器​​构造函数?这是正确的做法吗?

Rub*_*ate 1 c# asp.net-mvc asp.net-mvc-routing asp.net-mvc-4

我可能做的不对,因为我是这个框架的新手,希望你能帮忙^^

正如您在下面的代码中看到的那样,在每个操作中,我都会找到要更新的表,然后调用表中的方法。

public class TableController : Controller
{
    private Lobby L;

    public TableController()
    {
        L = Lobby.Instance;

    }

    public ActionResult Index(uint id)
    {
        Table T = L.Tables[id];
        return View(T);
    }

    public ActionResult AddPlayer(byte pos, uint id)
    {
         Table T = L.Tables[id];

        ...
        T.AddPlayer(p, pos);
        ...
    }
 ...
Run Code Online (Sandbox Code Playgroud)

}

但是我注意到我在每个方法中都在做同样的事情,所以我虽然可以将表变成一个属性,这样我就不需要为每个动作找到它。

我想要这样的东西:

public class TableController : Controller
{
    private Lobby L;
    private  Table T;


    public TableController(uint tableId)
    {
        L = Lobby.Instance;
        T = L.Tables[tableId];
    }

    public ActionResult Index()
    {
        return View(T);
    }

    public ActionResult AddPlayer(byte pos)
    {
        ...
        T.AddPlayer(p, pos);
        ...
    }
Run Code Online (Sandbox Code Playgroud)

这种方法有什么问题吗?

如果这在概念上没问题,我如何将表 ID 传递给我的构造函数?这不起作用:(

        routes.MapRoute(
                "Table",
                "Table_{tableId}/{action}/",
                new { controller = "Table", action = "Index"}
            );
Run Code Online (Sandbox Code Playgroud)

hai*_*770 5

通常,控制器构造函数用于注入依赖项,而不是数据。而且,现阶段,this.Request|Response|Session还有其他基本属性还在null

试试这个:

protected override void Initialize(RequestContext requestContext)
{
    var tableId = Convert.ToUInt32(requestContext.RouteData.GetRequiredString("tableId"));

    L = Lobby.Instance;
    T = L.Tables[tableId];

    base.Initialize(requestContext);
}
Run Code Online (Sandbox Code Playgroud)