Asp. NET tip: Replace Pagebase with MasterPage

Source: Internet
Author: User
Tags bool inheritance modify requires xpath
asp.net|erp| Tips

Objective:
Implement to replace the Pagebase in the project with the. cs file in MasterPage.

Motivation:
The motivation for writing this article comes from a project refactoring. In the. Net Framwork 2.0 b/S Architecture project, both Pagebase and masterpage technology are used to discover that each visit to the page, the page also access pagebase and masterpage, not only caused performance degradation, It may even be possible for future project functions to expand and adjust to bring logic errors.

Technical Links:
A technique commonly used in the Pagebase:.net Framework 1.1 that encapsulates the same functionality for multiple pages. The PageBase.cs class inherits from the System.Web.UI.Page class, the Web page in the project inherits from the PageBase.cs class, and implements the business functions in the call pagebase by overriding the page initialization method in the base class, such as URL parameter validation, save access, and so on. See Microsoft Official example Duwamishi).
The new feature in the Masterpage:.net Framework 2.0, which includes two files physically, is:. Master file (HTML tag),. cs file (C # code) ... Master file implementation display layer rendering,. cs file to achieve specific functions. Web pages that inherit from MasterPage can inherit the contents of the display layer in masterpage. Drawing the common header footer, customizing the unified layout, masterpage is a good choice.

Simulation Requirements:
Using masterpage technology, instead of Pagebase, the Address bar parameter verification is realized.
To make a simple explanation, the login table information in the database is shown below:

After you log on to the system, the URL address bar has parameters, as follows:
http://localhost:3730/MasterPageBaseDemo/TestPage.aspx?id=1001
The user manually modifies the URL address bar for the parameter:
http://localhost:3730/MasterPageBaseDemo/TestPage.aspx?id=1002
is considered an illegal operation, the system will automatically jump back to the login page.


First code iteration:


1. Refer to the traditional Pagebase method:
The traditional page approach is:
public class PageBase:System.Web.UI.Page
{
Public Pagebase ()
{
}
/**////<summary>
Entry method
</summary>
protected void Initialize ()
{
Insert Common business logic
}
}
Web page:
public partial class Testpage:pagebase
{
The traditional method of invoking Pagebase
/**/////<summary>
Overriding the base class Onpreinit () method, calling the generic authentication method
</summary>
<param name= "E" ></param>
protected override void OnInit (EventArgs e)
{
Base. Initialize ();
}
}
Refer to its practice to move the code in the Pagebase into the masterpage:
MasterPage.cs:
public partial class MyMasterPage:System.Web.UI.MasterPage
{
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
Calling validation methods
Initialize ();
}
}
}
Modify the code in the Web page to:
public partial class TestPage:System.Web.UI.Page
{
In the Pagebase method, invoke the method in master
/**////<summary>
Overriding the base class Onpreinit () method, calling the generic authentication method
</summary>
<param name= "E" ></param>
protected override void OnInit (EventArgs e)
{
Get a motherboard page reference
Mymasterpage mymasterpage = (mymasterpage) this. Master;
Calling common authentication methods in a master page
if (! IsPostBack)
{
Mymasterpage.initialize ();
}
}
Replace the Initialize () method in masterpage with the test code in the instance:
Step 1: Login The system with user name Zhangsan, login successfully,
The page shows welcome Zhangsan login.
URL address display:
http://localhost:3730/MasterPageBaseDemo/TestPage.aspx?id=1001
Step 2: Manually modify the URL address bar: as follows:
http://localhost:3730/MasterPageBaseDemo/TestPage.aspx?id=1002
The page does not show welcome Lisi login, but jumps back to the login page.
Reflection: Although functional realization, but there are not ideal link:
1. The quilt invocation method in master must be a public method;
2. Although you do not have to modify the Web page inheritance, you still need mechanical copy-paste to override the OnInit () method of the base class.
In order to eliminate these bosom flavours, it began:
Second code iteration:
To modify the code in MasterPage.cs:
public partial class MyMasterPage:System.Web.UI.MasterPage
{
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
Calling validation methods
Checklogin ();
}
}
/**////<summary>
Verify access is legitimate
</summary>
private void Checklogin ()
{
If the number in the URL or the number in the cookie
if (string. IsNullOrEmpty (request.querystring["id"])
|| String. IsNullOrEmpty (Cookieutil.readcookiebykey ("id"))
{
Response.Redirect ("Login.aspx");
}//if the number in the URL does not match the number in the cookie, return to the login page
else if (int. Parse (request.querystring["id"])!= Int. Parse (Cookieutil.readcookiebykey ("id"))
{
Response.Redirect ("Login.aspx");
}
}
After refactoring, the Web page can automatically invoke the validation method in its own Page_Load () method without any modifications, and set the validation method to private, only for MasterPage to masterpage, to improve security. At this point, the code seems to be more ideal, testing:
Step one: Use user name Zhangsan login system,
The user login page is still displayed.
The test failed.
Trace the code with a breakpoint and discover the code fragment in the Checklogin () method in the MasterPage.cs:
if (string. IsNullOrEmpty (request.querystring["id"])
|| String. IsNullOrEmpty (Cookieutil.readcookiebykey ("id"))
{
Response.Redirect ("Login.aspx");
}
Because the login page inherits from MasterPage, the validation method in MasterPage.cs is invoked automatically when the page loads, and its parameters do not satisfy the String.IsNullOrEmpty () method, and then jump back to the login page. The login page then calls the validation method in the base class again at load time, thus forming a dead loop.
In Pagebase technology, Web pages can be selected to inherit from Pagebase, and masterpage technology, in order to achieve a consistent display layer effect, Web pages on the inheritance masterpage selectivity is very bottom, and we should not adopt the new same display, It is obviously unreasonable to inherit a Web page that does not need to inherit the base class functionality without the masterpage of the validation code. To solve the problem, it began
Third iteration:
To introduce a configuration file:
<?xml version= "1.0" encoding= "Utf-8"?>
<pages>
<testpage>
<page title= "Testpage" url= "testpage.aspx" needvalidate= "true"/>
<page title= "Login" url= "Login.aspx" needvalidate= "false"/>
</testpage>
<adminpages>
<page title= "Page1" url= "~/admin/page1.aspx" needvalidate= "false"/>
<page title= "Page2" url= "~/admin/page2.aspx" needvalidate= "false"/>
</adminpages>
</pages>
You can see that the page that needs to be validated is identified (needvalidate= "true").
To create an XML data access class:
public class Xmldal
{
private static string FilePath = String. Empty;
Static Xmldal ()
{
Initialize profile path
FilePath = HttpContext.Current.Request.MapPath ("~/app_data/xml/" + "Pages.xml");
}
/**////<summary>
Get a list of pages that need to be validated
</summary>
<returns> List of pages to validate </returns>
public static ilist<string> Getvalidatepages ()
{
ilist<string> pages = new list<string> ();
If the specified configuration file exists
if (System.IO.File.Exists (FilePath))
{
Try
{
XmlDocument xmldoc = new XmlDocument ();
Xmldoc.load (FilePath);
Get configuration file root node
XmlNode root = xmldoc.documentelement;
String XPath = "/pages/testpage/page[@needvalidate = ' true ']";
XmlNodeList nodelist = root. SelectNodes (XPath);
Convenient node collection
foreach (XmlNode node in nodelist)
{
Pages. ADD (node. attributes["title"]. Value);
}
}
catch (Exception ex)
{
throw new Exception (ex. message);
}
}
return pages;
}
}
Refactor the code in MasterPage.cs and add a isvalidateneeded (string url) method to detect if the current page requires validation and modify the authentication method:
public partial class MyMasterPage:System.Web.UI.MasterPage
{
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
Calling validation methods
Checklogin ();
}
}
/**////<summary>
Verify access is legitimate
</summary>
private void Checklogin ()
{
Determine if the current access page requires authentication
if (isvalidateneeded (Request.rawurl))
{
If the number in the URL or the number in the cookie
if (string. IsNullOrEmpty (request.querystring["id"])
|| String. IsNullOrEmpty (Cookieutil.readcookiebykey ("id"))
{
Response.Redirect ("Login.aspx");
}//if the number in the URL does not match the number in the cookie, return to the login page
else if (int. Parse (request.querystring["id"])!= Int. Parse (Cookieutil.readcookiebykey ("id"))
{
Response.Redirect ("Login.aspx");
}
}
}
/**////<summary>
Verify that the current page requires validation
</summary>
<param name= "currentpage" > Current page name </param>
<returns> Whether validation status is required </returns>
private bool isvalidateneeded (string URL)
{
BOOL isneeded = false;
Getvalidatepages () method returns the list of required validation pages
ilist<string> pages = Xmldal.getvalidatepages ();
ienumerator<string> ie = pages. GetEnumerator ();
while (ie. MoveNext ())
{
If the current page needs to be validated
if (URL. Contains (ie. Current))
return Required validation Status
return isneeded = true;
}
return isneeded;
}
}
To test:
Step 1: Login The system with user name Zhangsan, login successfully,
The page shows welcome Zhangsan login.
URL address display:
http://localhost:3730/MasterPageBaseDemo/TestPage.aspx?id=1001
Step 2: Manually modify the URL address bar: as follows:
http://localhost:3730/MasterPageBaseDemo/TestPage.aspx?id=1002
The page does not show welcome Lisi login, but jumps back to the login page.

This is the end of my code iteration.
Code Download:
Http://www.cnblogs.com/Files/ayuan/MasterPageBaseDemo.rar
I have not written before the experience of technical articles, so the above text is inevitably obscure, and its own technical level is limited, may be some ideas are not too mature, welcome to your friends.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.