在我原来的帖子中,我正在考虑将用户信息传递给Controller
构造函数。我不希望Controller
取决于HttpContext
,因为这会使测试变得困难。
尽管我感谢Mystere Man对于他的解决方案,我希望以下备用解决方案可以帮助某人。我有一个小项目(大概有十几个控制器)所以还不错。
我基本上创建了定制ControllerFactory
从DefaultControllerFactory
继承:
public class MyCustomControllerFactory : DefaultControllerFactory
{
public MyCustomControllerFactory()
{
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
return null;
}
else
{
//Example of User Info - Customer ID
string customerIDStr = requestContext.HttpContext.Session["CustomerID"].ToString();
int customerID = Int32.Parse(customerIDStr);
//Now we create each of the Controllers manually
if (controllerType == typeof(MyFirstController))
{
return new MyFirstController(customerID);
}
else if (controllerType == typeof(MySecondController))
{
return new MySecondController(customerID);
}
//Add/Create Controllers similarly
else //For all normal Controllers i.e. with no Arguments
{
return base.GetControllerInstance(requestContext, controllerType);
}
}
}
}
我然后设置ControllerFactory
在Global.asax.cs
Application_Start()
方法。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new MyCustomControllerFactory());
}
P.S.我用Ninject等DI容器进行了研究,但我认为它们对于我目前的项目来说太复杂了。我会在几个月内看到它们,因为使用它们真的很有意义。
这里我真正的问题是如何将用户信息传递给控制器一旦验证?我想我的身份验证实施选项将被限制,一旦我解决这个问题。 –
@ O.O。 - 答案是你没有。如果您使用FormsAuthentication,那么身份验证将为您完成。如果你在'User.Identity.Name'中使用控制器'User'的属性,你将得到用户登录的用户名,然后你从数据库中查找你需要的其他信息。 –
@ O.O。 - 呃..我的意思是,如果你使用'FormsAuthentication',那么认证cookie管理就为你完成了,它还包括验证后续页面上的cookie,并填充'HttpContext.Current.User'全局变量(然后它将传播到控制器和视图)。 –