I'm fixing my friend's codes. And I have a problem with session value in masterpage.
I'm checking session is null or empty in masterpage and if it's null go to login page.
But other pages that created by masterpage never works.
if (Session["user"] != null && Session["user"] != "")
{ }
else
{
Response.Redirect("/Account/Login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
I tried with Session["user"].ToString() but same result.
And the otherpages have a other controls via this session so it always give error if you are not login.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
MaintainScrollPositionOnPostback="true" CodeFile="document.aspx.cs" Inherits="document" %>
Based on this:
But session control in back.master's page_load fire after default.aspx page_load so it gives me error the "session is null"
The root problem here is simple... You need to fully understand the ASP.Net page life-cycle
Take a quick look:
Basically your following assumption is wrong:
Then i create normal aspx page which name is default.aspx and is derived by back.master
From MSDN:
Master pages behave like child controls on a page: the master page Init event occurs before the page Init and Load events, and the master page Load event occurs after the page Init and Load events
Sadly an ASP.Net does not derive from a Master Page Why? because a Master Page is treated as a control so what really happens is that the master page is a child control of the Page
Alternatives:
Since you are checking if the user is authenticates, it would be better if you rely on the ASP.Net authentication and authorization API
Workarounds (if you insist to use your own authentication mechanism):
(Best recommendation) Create a custom HttpModule and check the Session object there. I think the event that best fits your needs is the: Application_AuthenticateRequest. This is a full list of events you can choose from: (BTW there's no need to create a new HttpModule, you could subscribe to events using the Global.asax file of your web application, use an HttpModule only if you would like to encapsulate the logic to reuse it)
Application_BeginRequest.
Application_AuthenticateRequest.
Application_PostAuthenticateRequest.
Application_DefaultAuthentication.
Application_AuthorizeRequest.
Application_PostAuthorizeRequest.
Application_ResolveRequestCache.
Application_PostResolveRequestCache.
Application_MapRequestHandler. Fired only when the server is running IIS 7 in Integrated Mode and at least >Net Framework 3.0
Application_PostMapRequestHandler.
Application_AcquireRequestState.
Application_PostAcquireRequestState.
Application_PreRequestHandlerExecute.
The page event handler is executed. (refer to the page life cycle)
Application_PostRequestHandlerExecute.
Application_ReleaseRequestState.
Application_PostReleaseRequestState
Application_UpdateRequestCache.
Application_PostUpdateRequestCache
Application_LogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
Application_PostLogRequest. Fired only when server is IIS 7 Integrated Mode and at least .Net Framework 3.0
Application_EndRequest.
For more info:
ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0
ASP.NET Application Life Cycle Overview for IIS 7.0
Create a generic page inheriting from Page and place the check code there in the PreLoad or Load event, both events would work and finally inherit all your pages from this page
(Not recommended) If you want to encapsulate the check inside the Master Page, you could use the Init event
IIS has standard methods for authentication and authorization.
If you want to restrict access to certain areas of your website if the user isn't logged in, then there are mechanisms in the configuration that allow for that:
In your web.config you can add:
<location path="LoginRequiredDir">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
This will automatically take users to the login page if they are not logged in.
Fix: It will solve your issue.
protected void Page_Init(object sender, EventArgs e)
{
if (Session["master"] != null)
{ }
else
{
Response.Redirect("login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
}
I also had similar issue faced. I used true to the Response.Redirect method so that the rest of load should gets terminated. Ref. I checked the session value in Page_Init of the master page as below.
public partial class Dashboard : System.Web.UI.MasterPage
{
protected void Page_Init(object sender, EventArgs e)
{
if (Session["RoleId"] == null || Session["RoleId"].ToString() == "")
{
Response.Redirect("/account", true);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
setUserInfo();
}
}
}
Hope it helps.
You define the above code Page_Load method in following way:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null && Session["user"].ToString() != "")
{
//do code here
}
else
{
Response.Redirect("/Account/Login.aspx?link=" + System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
}
Related
i have huge number of aspx pages. i want to fire a common function from all aspx page page load event but for that i need to add the function call in all page load event of all aspx page. so i am looking for a easy trick bu which i can make possible a function call from all page load event of all aspx page in my site.
so is it possible to hook page load event from out side or can we create a base page which will attached with all aspx page dynamically.
but i do not mean by base page like
public partial class MyBase: System.Web.UI.Page
{
}
public partial class index : MyBase
{
}
the above way i do not want to solve the problem bacuse if i follow the above way then i have to edit all aspx pages in my site. i need any easy trick to hook page load event.
please guide me.
EDIT
private void OnBeforeExecute(Object sender, EventArgs e)
{
var app = (HttpApplication) sender;
HttpContext context = app.Context;
//insert your code here
string sVal = BBAreman.CountryCookie.GetCookieValue();
if (sVal.Trim() == "")
{
Response.RedirectPermanent("~/country.aspx?ShowCountry=true", true);
}
}
i am checking cookie value...if found none then redirect to country.aspx. so when country.aspx load then again code try to redirect to country.aspx.....infinite loop start.
guide me how to code for this situation. thanks
Sounds like you need an HttpModule.
Your code then should look something like
public class MyModule : IHttpModule
{
public void Init(HttpApplication application)
{
//hook your onload event here. There are other events that could be more suitable
app.PreRequestHandlerExecute += OnBeforeExecute;
}
private void OnBeforeExecute(Object sender, EventArgs e)
{
var app = (HttpApplication) sender;
HttpContext context = app.Context;
//insert your code here
}
public void Dispose()
{
}
}
Do not forget to check out the module registration section in the link above.
Note: there are many more events that are fired in the asp.net pipeline, have a look here for a list of them. Maybe there is a more suitable event depending on what you need to do
EDIT
Since you posted the code, there are a few things you can do to improve this
DO NOT use RedirectPermanent in this case. A simple 302 Redirect is fine. Browsers tend to cache permanent redirects 'cause you know, they're permanent, no need to check again. So you end up with 2 infinite loops: a) the browser has cached the 301 and always redirects you to the country ballot screen, b) your code always redirects to the ballot screen anyway
You should insert some logic that checks whether the page is the ballot screen, and if so avoid redirection. Maybe something like this:
HttpContext context = app.Context;
if(context.Request.RawUrl.IndexOf("country.aspx",StringComparison.InvariantCultureIgnoreCase) > -1)
{
return;
}
//rest of your code here
An aside: you should have been able to figure this one out yourself. I took a look at your profile page, there are almost a thousand questions you asked, and the ones I sampled should be easy to research and resolve yourself. Something tells me you delegate all your programming to SO people. You get a -1 from me.
I have created a VS 2013 project using built-in asp.net Web Application Web Forms template. By putting a breakpoint in the Page_Load method of a page I can see the method is executed twice between pressing F5 and the page appearing. Why? And can I / should I stop this behaviour?
Apologies for not providing enough detail. The code is completely vanilla, untouched template code generated by VS Exp 2013 for Web.
The ASPX file is
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="mycompanyname.B1WebApp.About" %>
The ~/Site.Master has an empty Page_Load method (not sure this is relevant)
The code behind is
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Boolean Nothing;
}
}
You can avoid pageload function working on each postbacks by !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Your code here
}
}
A User control with this master page can also cause pageload execute twice...
This is part asp.net web forms, as a page posts back to itself whenever a server control is used on a page. It has been like this forever.
You need to do a check on page load:
if(!IsPostBack)
{
//Code for first time load
}
else
{
// code whenever you have a postback
}
There is a requirement in one of my project, where I need to change Master Page during run time.
I mean I need to apply check and on the basis of that check particular master page can be called to my native aspx page.
Please help me out for same.
Thanks in advance :)
For example:
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
Apply your conditionals as required. From here.
Yes. Set the MasterPageFile property only during the PreInit page event—that is, before the runtime begins working on the request (since the rendering of the page with the master page occurs prior to the Init event)
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "simple2.master";
}
If you try to set the MasterPageFile property in Init or Load event handlers, an exception is raised.
Yes it is possible, Implement like below
Dynamically Loading Master Pages in ASP.NET 2.0
To acheive this we need to write code in Page_PreInit before page gets render.
Put below code into your code behind:
if (Session["userType"] == "Admin") //check the user type
this.Page.MasterPageFile = "~/Admin.master";
else
this.Page.MasterPageFile = "~/User.master";
Hope this helps.
The problem is: When a user vists Default.aspx, the page loads the cached version of the Blog.ascx content (because it has hit the same page again within 600 seconds), the Page.Title code is not executed therefore the title remains empty instead of having <title>Title of Blog Post</title> like when it freshly loads the page the first time.
My asp.net website has Blog.ascx to handle loading the content of an individual blog post. Default.aspx contains the reference to and uses the Blog.ascx
The Blog.ascx page has custom caching:
<%# OutputCache Duration="600" VaryByParam="None" VaryByCustom="Url" %>
The custom caching, located at global.asax.cs is:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
switch (custom.ToUpper())
{
case "URL":
return context.Request.Url.ToString().ToLower().Trim();
default:
throw new NotImplementedException();
}
}
The Blog.ascx.cs Page_Load event handles the programmatic tag's value/content
protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "Title of Blog Post";
}
Any suggestions?
Have you considered using UserControls?
If you created a UserControl for the content of you page, you could move the OutputCache declaration to the control, thus freeing up the Page_Load event to set the Page title every visit.
Here is the sequence in which events occur when a master page is merged with a content page:
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx
So, my problem is:
I have one login page (not use master page), one master page, and hundreds of content page.
I check login session Session["loggedInUser"] in master page (if not logged in, redirect to login page)
So, when I don't log in, if I type the address of one content page, it must check login session in master page and redirect to login page, right? But it has two cases here:
If in content page, I don't use anything related to Session["loggedInUser"], it will redirect to login page, so, it's OK here!
The second case: if I use Session["loggedInUser"] to display Username in content page for example:
UserInfo loggedInUser = (UserInfo)Session["loggedInUser"];
it will return null object here, because the page_load in content page is fired before page_load in master page, so it thows null object instead of redirecting to login page.
I also tried Page_PreInit in master page but no help
protected void Page_PreInit(object sender, EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
}
Any suggestion?
Presumably, when you say you are using the Session["loggedInUser"] value, you are then calling .ToString() method or similar to display it?
In which case, you will need to check for a null object before using it. It would be best practice to check for the existance of the object before using any methods on it in any case, so:
if (Session["loggedInUser"] != null)
{ ... }
Only if you are certain that the code will never be executed without the Session object being instantiated can you use methods without checking for a null reference.
http://msdn.microsoft.com/en-us/library/03sekbw5.aspx
Finally I've come up with a solution:
I create a class BasePage like this:
public class BasePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
base.OnLoad(e);
}
}
And in the content page, instead of inheriting from Page, I change to BasePage and it works perfectly
Thanks for all of your support
Nice day ;)
You could check for Session["loggedInUser"] in the content Page's Page_PreRender() rather than Page_Load()or alternatively, do the master page check in the Page_Init() rather than Page_Load(). We had the same problem and went with the Master page Page_Init() option, so that we could still use Page_Load() in all the Content pages.
Edit: It's Page_Init() not PreInit().
I have 2 masterpages(1 for prelogin,2nd for afterlogin),home page is independent,logout page inherits postlogin page) in all postloginpage session chck if sessionnull(xyz)else(redirect loginpage) all this in Page_Init event of afterlogin.master................Successfull