Asp. NET implementation of pseudo-static Web page Method Summary _ Practical skills

Source: Internet
Author: User
Tags httpcontext

This article summarizes the asp.net to realize the pseudo static Web page method, shares for everybody to use for reference. The specific methods are as follows:

Method one: Using HttpHandler to implement URL rewriting (pseudo URL and pseudo static)

We sometimes see such an address: "http://www." Xxxx.com/show-12-34.html ", you may think that there is a file named" Show-12-34.html "under the root directory"/"of the site server, in fact it may not exist, and you may see the content is"/aspx/show.aspx? Type= 12&id=34 "The content, why should this do? There are several reasons: first, to enhance the friendliness of the URL, remember "show-12-34.html" is always better than "/aspx/show.aspx?type=12&id=34" remember it? The second is to facilitate the search engine included, many search engines are more optimistic about static HTML pages, such as: Baidu, followed by security considerations, because this hides the parameter "type", "ID." Isn't it fun?

In fact, this is done using URL rewriting, I will say below asp.net2.0 I know the simplest implementation method: By implementing the Interface "IHttpHandler" to take over the HTTP request, Follow me!

1. Add a class to the resource management scenario , the code for the class is as follows:

Class Urlrewriter Program list: Using System; 
Using System.Data; 
Using System.Configuration; 
Using System.Web; 
Using System.Web.Security; 
Using System.Web.UI; 
Using System.Web.UI.WebControls; 
Using System.Web.UI.WebControls.WebParts; 
Using System.Web.UI.HtmlControls; <summary>///urlrewriter URL rewrite class///Author:yoyo///</summary> public class Urlrewriter:ihttphandl ER//implement "IHttpHandler" interface {public urlrewriter () {////TODO: Add constructor logic//} public void ProcessRequest here (httpcon 
Text context) {try {//Get original URL mask off parameter string Url = CONTEXT.REQUEST.RAWURL; Establish regular expression System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex (@ "/show-(\d+)-(\d+) \. 
. + ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); Match with a regular expression System.Text.RegularExpressions.Match m = Reg.match (Url,url.lastindexof ("/"));//start with the last "/" to match the IF (M. 
Success)//Match succeeded {String Realpath = @ "~/aspx/show.aspx?type=" + m.groups[1] + "&id=" + m.groups[2]; ContExt. 
Response.Write (Realpath); Context.rewritepath (Realpath);//(RewritePath used in no Cookie session state.) 
) Context.Server.Execute (Realpath); 
else {Context.Response.Redirect (Context.Request.Url.ToString ()); 
The catch {Context.Response.Redirect (Context.Request.Url.ToString ()); }///<summary>///the member required to implement the IHttpHandler interface///</summary>///<value></value>///Author 
: Yoyo public bool IsReusable {get {false;}

 }
}

2. Add the following setup items to the Web.config file

Add the following code under the <system.web> node:

<add verb= "*" path= "*/show-?*-?*.aspx" type= "Urlrewriter"/>

Explain:

Verb refers to the permitted action "get", "POST", "put" in one or several, the asterisk "*" means all allow;

Path is a matching path that supports a simple wildcard character;

Type refers to the class name of the binding and includes the namespace, if any;

By the way, first you have to create a Web Form "show.aspx" under Directory "aspx," because this file is the page that actually accepts the request and displays the relevant content.

Ok! , compile, open the Web site input address http://localhost:80/show-12-34.aspx visit, check to see if the "/aspx/show.aspx?type=12&id=34" content?!

Above I set up a matching ASPX file because the HTML extension is not owned by the ASP.net, and if you want to take over the HTML request,
Please map the IIS extension. html to "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll",
Then change the above aspx to HTML:

<add verb= "*" path= "*/show-?*-?*.html" type= "Urlrewriter"/>

Now open the Web site input address http://localhost:80/show-12-34.html visit ~!

Method Two: Address rewriting, using pseudo static, page postback processing

When making a website page, sometimes for the user's experience and search engine included, many websites often use pseudo static address rewrite, or URL address rewrite method, to be such as: myebook.aspx?id=1,myebook.aspx?id= 2myebook.aspx?id=3 and other dynamic pages with parameters disguised as a static page, for example, the above disguise become my1.html,my2.html,my3.html and so on!

The starting point is very good, not only conducive to user experience, but also conducive to inclusion, is to kill both!

The benefits have been said, now to talk about the problems of using this approach, the problem is, when you use the pseudo static technology page has the button, needs to submit the content, this time, once with the server has the postback action, then, the address bar inside displays the webpage address is no longer is disguises the my1.html, my2.html,my3.html wait and pull, but become myebook.aspx? Id=1,myebook.aspx?id=2myebook.aspx?id=3 and so on, so that will make users who do not know how to make Web pages feel uneasy, they will think that they are in a cheater site, that they submitted data are another site to steal, in short, To give them the feeling is that such a site is deceptive; it's likely that they'll never be able to go to your site again!!! .........

Below I personally solve the above issues of experience to do as follows, I hope to help the vast number of users to solve the problem!

Solve the above problems, there are many ways to use JavaScript prohibit postback, there will be the page

To wait for a variety of methods, anyway, can be changed places, have been used, and, such articles more, but it is difficult to achieve, on my temper just, prefer the direct approach, as little as possible to change the place, so as to avoid future mistakes trouble;

The first step: Open your Web site, create a new class, the file name is generally the case: MyActionlessform.cs

Step Two: The code for the class is as follows:

Using System; 
Using System.IO; 
Using System.Web; 
Using System.Web.UI; Namespace Myurl {public class Myolpage:page {public Myolpage () {} protected override void Rende R (HtmlTextWriter writer) {if (writer is System.Web.UI.Html32TextWriter) {writer = new Formfi Xerhtml32textwriter (writer. 
      Innerwriter); else {writer = new Formfixerhtmltextwriter (writer. 
      Innerwriter); Base. 
    Render (writer); } internal class FormFixerHtml32TextWriter:System.Web.UI.Html32TextWriter {private string _url;//Disguise The URL internal formfixerhtml32textwriter (TextWriter writer): base (writer) {_url = Httpcontext.cur Rent. 
    Request.rawurl; public override void WriteAttribute (string name, string value, bool encode) {if (_url!= null &&am P 
      String.Compare (name, "action", true) = = 0) {value = _url; Base. WriteattriBute (name, value, encode); 
    } internal class FormFixerHtmlTextWriter:System.Web.UI.HtmlTextWriter {private string _url; Internal Formfixerhtmltextwriter (TextWriter writer): base (writer) {_url = HttpContext.Current.Request . 
    Rawurl; public override void WriteAttribute (string name, string value, bool encode) {if (_url!= null &&am P 
      String.Compare (name, "action", true) = = 0) {value = _url; Base. 
    WriteAttribute (name, value, encode); 

 } 
  } 
}

After that, compile the class file into a MyActionlessform.dll file and refer to him in the site's project,

The third step: Open the page with postback operation, will be one of the: System.Web.UI.Page change to: Myurl.myolpage, that is, once and for all, no longer worry about the return of the real address to scare away the net friend pull!

At this point, can be more than half a little, the next question came, what the problem, you run your site, is not the following error!

CS0433: Type "Myurl.myolpage" also exists in "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ temporary asp.net files\schoolit\ 3266aab1\aca2fc74\app_code.2-69spm5.dll "and" C:\WINDOWS\ microsoft.net\framework\v2.0.50727\temporary ASP.NET Files\ Schoolit\3266aab1\aca2fc74\assembly\dl3\4d107fc6\00b753fe_ea19c801\ MyActionlessform.DLL "in

This is basically the mistake, for such a mistake, there are many solutions, some places say, delete the temporary use of the folder, delete a namespace and so on operation, I have tried, but not the fruit, and then I think of myself, this error is nothing more than two files exist at the same time, but can not be repeated use , the solution that is not simple, deactivate one, only use one on the line

Above, we have not built a MyActionlessform.cs, it exists in the App_Code folder, the other one is MyActionlessform.dll, two file content exactly the same, do it, we don't need to MyActionlessform.cs, we just need MyActionlessform.dll, then, to find ways to get the former not to have to do (I suggest that this document should be excluded from the project, do not advocate the direct deletion of the document, because it may be used later), my practice is, In the project directly out of the MyActionlessform.cs file, after testing, the results have been completed!!!!

Method Three: Using Mircosoft URLRewriter.dll to implement page pseudo static

Yesterday, I posted an article that uses ISAPI filters to implement URL pseudo static, and I did it on the content of the article, but I didn't do it, so it seems that this method does not use Microsoft URLRewriter.dll This method is good, at least I personally feel, spent a night of time, finally research out how to use this DLL file to asp.net page to achieve static, in fact very simple.
First, obtain Mircosoft URLRewriter.dll:
Get Mircosoft URLRewriter.dll can go to http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx?mfr=true
Here, select [Download the source code], download finished, import the project, I do not have any changes to the project, retained the original way of rewriting, and then directly in the VS2005 to generate a. dll file on it.
second, use the DLL file :

Add a reference and fix it.

third, the design of the page, here is not to repeat, I will put a download package, interested friends download to see it, the code to write more chaotic.

Four, web.config configuration
This is critical and is key to the success of Statics.

<?xml version= "1.0"?> <configuration> <configSections> <section name= "Rewriterconfig" type= "UR" LRewriter.Config.RewriterConfigSerializerSectionHandler, Urlrewriter "/> </configSections> < Rewriterconfig> <Rules> <RewriterRule> <lookfor>~/web/new/type/(. [ 0-9]*) \.html</lookfor> <SendTo>~/web/new.aspx?id=$1</SendTo> </RewriterRule> <r 
   Ewriterrule> <LookFor>~/web/index.html</LookFor> <SendTo>~/web/index.aspx</SendTo> </RewriterRule> </Rules> </RewriterConfig> <system.web>  

Here is a brief introduction:

<RewriterConfig> 
  <Rules> 
  <RewriterRule> 
   <LookFor> to find the mode </LookFor> 
   <SendTo> string to be used to replace the pattern </SendTo> 
  </RewriterRule> 
  <RewriterRule> 
   < Lookfor> the pattern to find </LookFor> 
   <SendTo> the string to use to replace the pattern </SendTo> 
  </RewriterRule> 
  </Rules> 
</RewriterConfig> 

The httphandlers setting is primarily in line with the request of IIS to redefine the processing, which is also more critical, if there is no reasonable httphandlers, then access will certainly fail.

About regular expressions, you can search in Baidu: "Common regular expression", there will be a lot.

Five. Configure IIS resolution. html files

Right-click My Computer--> management--> expand ' Services and Applications '-->internet Information Services--> Find your shared directory--> right-click Properties--> Click ' Configure '--> map below--> Find. aspx executable path copy path--> paste path--> extension ". html"--> then check the file to see if the existence of the tick off this is OK, if you encounter the "OK" button is invalid, you can use the keyboard event edit path to resolve.

This article example code points this site to download.

It is believed that this article has certain reference value to the ASP.net program design of everybody.

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.