Reputation: 51
How can I run a script in every aspx file?
This is what I want to be run at the beginning of every aspx file. How can I do that?
I dont want to copy and paste it in every file I have
if (CUser.LoginID == "")
{
Response.Redirect("login.aspx");
}
Upvotes: 0
Views: 224
Reputation: 1800
I could answer your question directly. However, it is common practice to put the authentication redirect in the web.config. It would be in a section like this:
<authentication mode="Forms">
<forms name=".SAMPLESITEAUTH" loginUrl="~/Login.aspx" protection="All" timeout="20" slidingExpiration="true" path="/" cookieless="UseCookies"></forms>
</authentication>
The user would be redirected to the url listed in loginUrl.
Upvotes: 0
Reputation: 26
If you want to authenticate a user on a page request, as your code suggest, you should check out asp.net form authentication.
http://www.asp.net/security/tutorials/an-overview-of-forms-authentication-cs
If you want to run an arbitrary set of functions on every page request, you can either:
1) Create a base page that inherits from System.Web.UI.Page, override the OnInit method and stick your code in there. Make sure your pages now inherit from that new base page.
or
2) Modify the Global.asax.cs by adding your code in the Application_BeginRequest method.
Upvotes: 0
Reputation: 2697
Create a BasePage.cs class:
public class BasePage:System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
if (CUser.LoginID == "")
{
Response.Redirect("login.aspx");
}
}
}
And then every aspx file change from:
public partial class pagename: System.Web.UI.Page
to
public partial class pagename: BasePage
and you are done. It should work fine for you. It works excellent for my user login tracking and redirecting if user is not logged.
Upvotes: 0
Reputation: 218887
The easiest way would probably be to create a base page class which inherits from System.Web.UI.Page
and runs this code in Page_Load
. Then, change each of your pages to inherit from the base page class. Then, any time a page loads, it will execute Page_Load
in both the base class and in the page class.
Probably a better way to do this, but slightly more complex, is to implement an HttpModule. The idea behind an HttpModule is that it will intercept the request, do something custom, and then pass the request along as normal.
Upvotes: 2
Reputation: 10257
You would want to use an HTTP module for this.
HTTP modules are registered for a web application and receive events at certain points throughout the lifecycle of a request.
Since this looks to be related to site authentication, you could use the AuthenticateRequest
event to check your CUser.LoginID
property and redirect if necessary.
Upvotes: 1