C# 在ASP.NETMVC中保持干燥
目前,我的第一个ASP.NETMVC应用程序已经运行了大约两周半,到目前为止,我非常喜欢它 此当前项目是ASP.NETWebForms项目的一个端口,我正在尝试维护其功能。一切进展顺利 然而,我发现自己在重复。。。我自己 例如,在我的BaseController类、我的BaseViewPage、我的BaseViewUserControl和我的BaseViewMasterPage中,我有以下代码:C# 在ASP.NETMVC中保持干燥,c#,asp.net-mvc,dry,C#,Asp.net Mvc,Dry,目前,我的第一个ASP.NETMVC应用程序已经运行了大约两周半,到目前为止,我非常喜欢它 此当前项目是ASP.NETWebForms项目的一个端口,我正在尝试维护其功能。一切进展顺利 然而,我发现自己在重复。。。我自己 例如,在我的BaseController类、我的BaseViewPage、我的BaseViewUserControl和我的BaseViewMasterPage中,我有以下代码: protected LanLordzApplicationManager AppManager {
protected LanLordzApplicationManager AppManager
{
get
{
if(Session["Application"] == null)
{
Session["Application"] = new LanLordzApplicationManager(Server.MapPath("~/"));
}
return (LanLordzApplicationManager)Session["Application"];
}
}
protected User CurrentUser
{
get
{
if (Session["UserID"] == null && this.Request.Cookies["AutoLogOnKey"] != null && !string.IsNullOrEmpty(this.Request.Cookies["AutoLogOnKey"].Value))
{
this.CurrentUser = this.AppManager.RecallUser(this.Request.Cookies["AutoLogOnKey"].Value, Request.UserHostAddress);
}
if (Session["UserID"] == null)
{
return null;
}
else
{
return this.AppManager.GetUserByUserID((long)Session["UserID"]);
}
}
set
{
Session["UserID"] = value.UserID;
}
}
现在,这不是漂亮的代码。我想把它修好一点,但是现在,我在四个地方修好它。事实上,它一直是几个bug的来源,这意味着要在所有四个地方再次修复它
您建议我如何保持系统干燥?请注意,由于多种原因,会话中必须保留这两个对象。在App_代码中,创建一个类“BaseUtils”或类似的类,包含该功能;然后你只需要在需要的地方包括引用它
public class BaseUtils
{
public static LanLordzApplicationManager getAppMgr()
{
HttpSession Session = HttpContext.Current.Session;
if(Session["Application"] == null)
{
Session["Application"] = new LanLordzApplicationManager(Server.MapPath("~/"));
}
return (LanLordzApplicationManager)Session["Application"];
}
}
在你的页面上
protected LanLordzApplicationManager AppManager
{
get
{
return BaseUtils.getAppMgr();
}
}
同样,对于其他两种方法…您可以从BaseViewPage、BaseViewUserControl和BaseViewMasterPage中删除代码。渲染视图时使用的所有数据都可以作为viewdata从控制器传递给它们,viewdata已在所有视图中可用。这将使您的代码至少集中到控制器基类。使用mixin
interface IWebRequestable {
HttpWebRequest Request {get;} // Right class? Not sure.
}
public class BaseUserControl : UserControl, IWebRequestable {}
public class BaseController : Controller, IWebRequestable {}
public class BasePage : Page, IWebRequestable {}
public static class CurrentUserMixin {
public static User GetCurrentUser(this IWebRequestable RequestObject) {
// Put your User code here
}
}
我建议您将神奇的字符串“UserID”、“Application”等移动到常量,或者为会话对象使用强类型对象包装器。某些视图逻辑基于CurrentUser对象。在大多数情况下,我不想从控制器传递这些信息。也就是说,我希望用户能够普遍访问。如果您有一些需要的数据可以更全局地使用,那么您可以始终附加一个来填充每个操作调用、每个控制器或每个操作方法的数据。