ASP.NET常用函数
我有一个复杂的 ASP.NET 项目 (ASP.NET 2.0),我正在尝试稍微重构一下代码。
每个页面都扩展一个名为 GenericPage 的基页面,该页面具有一组在页面生命周期中使用的函数(访问 session/HttpApplicationState 对象的函数)。还有相当多的用户控件执行类似的操作,但扩展了单独的基类。
我们开始重新实现大量代码以使用 Web 服务,并且它们需要访问相同的功能。 WebServices 将扩展 GenericWebService。
鉴于两者不能从同一个类扩展(一个扩展 Page 一个扩展 WebService),那么构建这一点的最佳方法是什么?我不想在 3 个单独的基类中重复代码,因为它变得越来越难以维护。
是否有一个可以放置这些非静态函数的共同位置?
谢谢
I've got a complicated ASP.NET project (ASP.NET 2.0) and i'm trying to refactor the code a little.
Every page extends a base page called GenericPage which has a set of functions which are used in the page life-cycle (functions which access the session/HttpApplicationState object). There are also quite a few user controls which do a similar thing but extend a separate base class.
We are starting re-implement a lot of the code to use WebServices and they need to have access to the same functions. The WebServices will extend GenericWebService.
What's the best way to architect this given that both cannot extend from the same class given that one extends Page and one extends WebService? I don't want to duplicate the code in 3 separate base classes as it is getting increasingly difficult to maintain.
Is there a common place that I can put these non-static functions?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个使用 HttpContext.Current 来访问会话等的类。此类不需要从任何东西派生,您只需将其注入(或以其他方式实例化)到您的基本页面和基本 Web 服务中。
以下是该类的示例;我有一个用于轻松访问 Session 对象的辅助属性,以及一个存储当前用户 ID 的简单属性。您可能需要更多的错误处理,或者访问会话以外的其他内容,但如何执行更多操作应该非常简单。
然后在您的 Basepage 中:
最后一点是更改直接访问会话的所有当前 BasePage 属性,改为通过 WebSession 属性访问,或者更改所有引用代码以获取它(从 BasePage 中删除帮助器属性) 。
You can create a class that uses HttpContext.Current to access the session and such. This class doesn't need to descend from anything, and you just inject (or otherwise instantiate) it into your basepage and base web service.
Here's an example of what the class might look like; I have a helper property for accessing the Session object easily, and a simple property storing the current user ID. You may want more error handling, or to access things other than the session, but it should be pretty straightforward how to do anything more.
Then in your Basepage:
The last bit would be either changing all of your current BasePage properties that are accessing the Session directly to instead access via the WebSession property or to change all the referring code to get it (removing the helper properties from the BasePage).