Skip to main content
 首页 » 编程设计

c#之如何将参数传递给 Controller 构造函数这是正确的做法吗

2024年02月13日12dudu

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

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

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); 
        ... 
    } 
 ... 

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

我想要这样的东西:

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); 
        ... 
    } 

这种做法有什么问题吗?

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

        routes.MapRoute( 
                "Table", 
                "Table_{tableId}/{action}/", 
                new { controller = "Table", action = "Index"} 
            ); 

请您参考如下方法:

通常,Controller 构造函数用于注入(inject)依赖项,而不是数据。此外,在这个阶段,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); 
}