How to have a single "HelperClass.IsLoggedIn()" method for the entire ASP.NET web project?
This is a common need I have on every page:
if (session["LoggedIn"] == null || ((bool)session["LoggedIn"] != true))
....//user is not logged in. return.
I was wondering, is there a way I can create a class "Helper" with a method signature bool IsLoggedIn()
and call that method from a page so th开发者_JAVA技巧at automatically it can check if the page it was called from has the session["LoggedIn"]
set to true
? Something like this:
class Helper
{
public bool IsLoggedIn()
{
System.Web.UI.Page page = ***FindCallerPageSomeHow***();
if(page.session["LoggedIn"] == null || ((bool)page.session["LoggedIn"] != true))
return false;
return ((bool)page.HpptContext.Session["LoggedIn"] == true);
}
}
Ofcourse, I could try implementing an interface for each codebehind class, but thats repetitive. Also, I could pass in the HttpContext
for IsLoggedIn
, but that's a bit of clutter..
Any ideas? Is there a simple-to-implement pattern for this?
If you want to use this approach I would probably add a extension method on the session. But using formsauthentication is usually a lot easier.
Update
Btw, here is the extension method:
public static bool IsSignedIn(this HttpSessionState session) {
//Use the session to check if the user is signed in
}
Then you can use it like this:
if(Page.Session.IsSignedIn()) {
//Code
}
You could always have a static class in a library somewhere, but my favorite technique is simply to create your own Page class and add properties or override events there.
public class myPage : System.Web.UI.Page
{
public void myPage()
{
}
public bool IsLoggedIn()
{
System.Web.UI.Page page = ***FindCallerPageSomeHow***();
if(page.session["LoggedIn"] == null || ((bool)page.session["LoggedIn"] != true))
return false;
return ((bool)page.HpptContext.Session["LoggedIn"] == true);
}
}
Then in the code behind of your actual page, you would have
public partial myAspxPage : myNamespace.myPage
{
}
As an example, my page class usually contains a public property called ValidUser that contains pertinent user information (so I don't have to keep looking it up). If that value is null, then I don't have one. If it's not, then I have what I need. Then whenever I create a new page in my site, I just have it inherit my page class instead of the default.
EDIT: Added your method in for a little more clarity.
Why not put the code in the master page? That way any pages that need to be tested for the user being logged in can inherit from that master page and all is handled automatically. Otherwise, you're just repeating yourself in the code for every page.
I would create a base class called BasePage which would inherit from System.Web.UI.Page. I would then have the codebehind class inherit from BasePage.
In BasePage, you just add a method called IsLoggedIn(), and you can call it from anywhere within your code behind class.
精彩评论