ASP.NET - 执行某些代码的全局位置?
我有一个 .net 新手问题。
在每个页面加载之前编写一些全局执行的代码的好地方在哪里?我要做的一些操作是:
a)打开数据库连接 b) 检查会话以查看用户是否登录 c)也许初始化一些对象
我正在考虑在主文件中执行此操作,但不确定这是否是一个好主意。也许对于列出的每个操作,.Net 中可能已经有一个功能可以做到这一点,这样我就不必“重新发明”轮子。
I have a newbie .net question.
Where would be a good place to write some code that executes globally before each page load? Some operations that I would be doing are:
a) open a database connection
b) check the session to see if user is logged in
c) maybe initialize a few objects
I was thinking of doing this in a master file, but wasn't sure if that's a good idea. And maybe for each of the operations listed, maybe there's a feature in .Net that does it already, so that I don't have to "re-invent" the wheel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将创建一个所有页面都继承自的基页(母版页除外,因为它们具有不同的基类),
然后您可以覆盖基页上的 PreLoad 并在那里进行检查。
I would create a base page that all pages inheriet from (except master pages as these have a different base class)
You could then override PreLoad on the base page and do your checks in there.
您可以创建一个派生自
Page
的基类,并具有执行所需操作的Page_Load
实现。然后您必须更改所有页面以从这个新基类继承。You could create a base class that derives from
Page
, and has an implementation ofPage_Load
that performs the operations you want. Then you have to change all of your pages to inherit from this new base class.这将是 Global.asax 文件。
That would be the Global.asax file.