Reputation: 1522
I have a created a Simple LOGIN form...I want to Check Session["UserId"] is null or not...on every page load.
Instead of writing on every Page to Check Session["UserId"] is null or not.
what is the alternative way to write a common Code and call every page except LOGIN and REGISTRATION Form
if Session["UserId"] is null then i can easily Redirect to LOGIN Form or Else the Code is ongoing
If Possible you can give me Code with example.. Thank You!!
Upvotes: 5
Views: 720
Reputation: 4249
I usually create a class MyBasePage
, inheriting from System.Web.UI.Page, and put there all (or most) of the common logic shared by all pages in my web application.
When creating a new aspx page, you have to change its declaration so it inherits from MyPageBase
and not from Page
Then MyBasePage
has a virtual method (or property) RequiresLogin
, which returns true.
For Login and registration form, you override it returning false.
Finally, in the Load handler for MyPageBase
, you add something such:
if (RequiresLogin && !UserIsAlreadyAuthenticated)
Response.Redirect ("Login.aspx");
You can extend this pattern to handle what you think should be common to all of your pages
Upvotes: 1
Reputation: 1350
use this code in Global.asax:
public class Global : System.Web.HttpApplication
{ ...
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
// CheckSession() inlined
if (context.Session["UserId"] == null)
{
context.Response.Redirect("Login.aspx");
}
}
...
}
Upvotes: 5
Reputation:
The first thing that comes to mind are attributes. Or better; create your own attribute. Check out this link: https://learn.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes Maybe it gives you an idea
Upvotes: 0