5

目前,我的第一个 ASP.Net MVC 应用程序大约有两个半星期的时间,到目前为止,我很喜欢它。

这个当前项目是 ASP.Net WebForms 项目的一个端口,我正在努力维护功能。一切顺利。

然而,我发现自己在重复……我自己。

例如,在我的 BaseController 类、BaseViewPage、BaseViewUserControl 和 BaseViewMasterPage 中,我有以下代码:

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

现在,这不是漂亮的代码。我想稍微修一下,但截至目前,我在四个地方修了它。事实上,它是几个错误的来源,这意味着要再次在所有四个地方修复它。

你会如何建议我保持这个系统干燥? 请注意,这两个对象都必须保留在会话中,原因不止两个。

4

3 回答 3

4

在 App_Code 中,创建一个包含该功能的类“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();
    }
}

同样对于其他两种方法...

于 2009-06-09T02:54:24.290 回答
4

您可以从 BaseViewPage、BaseViewUserControl 和 BaseViewMasterPage 中删除代码。用于渲染视图的所有数据都可以作为视图数据从控制器传递给它们,这些数据已经在所有视图中可用。这至少将您的代码集中到控制器基类中。

于 2009-06-09T03:33:36.723 回答
4

使用混合!

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
    }
}
于 2009-06-09T03:43:28.003 回答