1

我最近才开始使用 ASP.NET 进行开发,尽管我已经使用 C# 好几年了。我第一个使用 ASP.NET 的方法是使用 MVC 4,但现在我发现自己正在处理一个使用普通 ASP.NET 页面的项目。我不知道一般框架是如何工作的。

具体来说,我不知道如何在 ASP.NET 页面中实现装饰器模式。我有一个 Product.aspx 页面,我必须向它添加一个功能。我认为装饰器模式最好基于任务要求,我立即想出了如何在 MVC 中使用它,因为执行的实际逻辑在于控制器动作:在那里我将实例化我的装饰器对象。

但我不知道如何在 ASP.NET 中做到这一点。据我所见,当浏览器请求 Product.aspx 时,“某事”创建了一个 Product 类的对象(派生自 Page),然后再装饰它为时已晚。

因此是否可以装饰整个 ASP.NET 页面(不仅仅是背后代码使用的对象)?我该怎么做?

4

2 回答 2

2

我不确定你想装饰什么,但是;

您可以创建一个 HttpHandler 来处理特定请求,如下所示

public class MyHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.RawUrl.Contains("product.aspx"))
        {
            // may be you can execute your decorate business here
        }
    }

    public bool IsReusable { get { return false; } }
}

或者您可以使用 Global.asax 的 OnBeginRequest 事件,如下所示

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterOpenAuth();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        base.BeginRequest += OnBeginRequest;
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        if (Request.RawUrl.Contains("product.aspx"))
        {
            //execute your business here..
        }
    }
于 2013-11-07T12:09:33.177 回答
1

首先,根据您在问题下方的评论,我可以说您应该将您的展示柜实现为网络用户控件(ascx)

您可以按如下方式装饰您的 ShowCase,

public partial class ShowCase : System.Web.UI.UserControl, IShowCase
{
    protected void Page_Load(object sender, EventArgs e){}
    public void ApplyConfiguration(IConfiguration configuration)
    {
        throw new NotImplementedException();
    }
}

public interface IShowCase
{
    void ApplyConfiguration(IConfiguration configuration);
}

public abstract class Decorator : IShowCase
{
    protected IShowCase ShowCase;

    protected Decorator(IShowCase showcase)
    {
        ShowCase = showcase;
    }

    public virtual void ApplyConfiguration(IConfiguration configuration)
    {
        ShowCase.ApplyConfiguration(configuration);
    }
}

public class ShowCaseDecoratorA : Decorator
{
    public ShowCaseDecoratorA(IShowCase showcase) : base(showcase){ }

    public override void ApplyConfiguration(IConfiguration configuration)
    {
        base.ApplyConfiguration(configuration);
        //depending on the configuration, do something..
        ShowCase.Visible = false;
    }
}

public interface IConfiguration
{
    //configuration
}

然后,从使用 ShowCase 用户控件的页面内部,您可以执行以下操作,

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        IConfiguration configuration = ConfigurationFactory.Get();
        new ShowCaseDecoratorA(this.ShowCase).ApplyConfiguration(configuration);
    }
}

我希望这能给你一些启发。。

于 2013-11-07T13:04:28.413 回答