Implementation of bidirectional rewriting of asp.net URL

Source: Internet
Author: User
Keywords Nbsp; http xml implementation can

When we are developing a Web program, in order to search engine optimization (SEO), we often need to optimize the access address of the web, such as modifying http://localhost/Default.aspx?tab=performance to http:// Localhost/default_performance.aspx, the latter address can be better searched by search engines, so as to achieve the goal of search engine optimization. Microsoft has an open source class library Urlrewriter can easily implement URL rewriting, by configuring the mapping table in the Web.config file to redirect the user's request to the specific page, I am using urlrewriter URL rewrite invalid The article details how to use this class library, which is performed through ASP.net httpmodules or httphandles, but if the host server for the Web site does not support asp.net httpmodules and httphandles, Then the functionality is invalidated and we can redirect the URL via the Application_BeginRequest event in global. On the basis of the Urlrewriter class library, this paper makes an improvement and gives a relatively complete solution.

Our improvement is based on urlrewriter, so urlrewriter original things as long as can be used, we can directly take over, of course, bad things to abandon!

Urlrewriter mapping table is written directly in the Web.config file, to allow Web.config to recognize the mapping table, you must add section in the configsections sections to tell the program how to correctly parse Web.config unrecognized content, such as the original URLREWR ITER needs to be added to the web.config. I think this is not a good way, first of all, you need to write a class library to parse the XML, and in the Web.config configuration, we can completely eliminate this step. The URL's mapping table can be written separately into an XML file, loaded into the application cache when the program runs, and sets a cache file dependency so that it can take effect whenever the administrator modifies the mapping table.

In addition I want to support bidirectional rewriting of URLs, the two URLs mentioned above, when the user enters the second URL, the program sends the request to the first URL, but the URL displayed in the browser does not change; When the user enters the first URL, it automatically jumps to the second URL. The second URL is displayed in the browser, but the request is still the first URL. Does that sound a little round? It doesn't matter, it's really simple, the basic requirements of the original site is that many of the pages in the visit with a lot of parameters, do URL rewrite to replace the new URL, then the old URL can still be used, the customer is thinking is when the original old URL can automatically jump to the new URL. This is the URL of bidirectional rewrite! These two methods can be implemented separately through the Context.rewritepath () and Context.Response.Redirect () methods, the following we look at the specific implementation.

The first is the implementation of the mapping table. I have made a little change on the basis of Urlrewriter original mapping table, that is to add a Isdirect property to Rewriterrule, this attribute optional, the default value is False, if the user requested URL match will be a jump, otherwise just make the request mapping.

XML version= "1.0"?>


<rewriterconfig xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=" http://www.w3.org/2001/ Schema ">


<Rules>


<ReWriterRule>


<lookfor>~/default_ (w) \.aspxlookfor>


<SendTo>~/Default.aspx?tab=$1SendTo>


Rewriterrule>


<rewriterrule isdirect= "true" >


<lookfor>~/default\.aspx\?tab= (w) lookfor>


<SendTo>~/Default_$1.aspxSendTo>


rewriterrule>


rules>


rewriterconfig>

The mapping table supports regular expressions, and the following are the corresponding entity classes that are used for deserialization.

using System;


using System.Collections.Generic;


using System.Linq;


using System.Web;





namespace Urlrewritertest


{


[Serializable]


public class Rewriterconfig


    {


Public rewriterrule[] Rules;


    }





[Serializable]


public class Rewriterrule


    {


private bool _isredirect = false;





[System.Xml.Serialization.XmlAttribute ("Isdirect")]


public bool Isredirect


        {


get {return _isredirect}


set {This._isredirect = value;}


        }


public string LookFor {get; set;}


public string SendTo {get; set;}


    }


}

The following class is used to get the mapping table, which, when the program is first run, places the results of the mapping table deserialization into the global application cache.

using System;


using System.Collections.Generic;


using System.Linq;


using System.Web;


using System.Xml.Serialization;


using System.IO;


using System.Web.Caching;





namespace Urlrewritertest


{


public class Rewriterconfiguration


    {


public static Rewriterconfig getconfig (string filename)


        {


if (httpcontext.current.cache["rewriterconfig"] = = null)


            {


rewriterconfig config = null;


//Create An instance of the XmlSerializer specifying type and namespace.


XmlSerializer serializer = new XmlSerializer (typeof (Rewriterconfig));





//A FileStream is needed to read the XML document.


using (Stream reader = new FileStream (filename, filemode.open))


                {


Declare an object variable of the type to be deserialized.


config = (rewriterconfig) serializer. Deserialize (reader);


                }


HttpContext.Current.Cache.Insert ("rewriterconfig", config,


new CacheDependency (filename));


            }


Return (Rewriterconfig) httpcontext.current.cache["Rewriterconfig"];


        }


    }


}

We still need methods in the RewriterUtils class in the original Urlrewriter class library, but the Rewriteurl method has been slightly altered to add a isredirect parameter. To determine whether to execute the Context.rewritepath () method or the Context.Response.Redirect () method, the following is the source code.

using System;


using System.Collections.Generic;


using System.Linq;


using System.Web;





namespace Urlrewritertest


{


public class RewriterUtils


    {


        /// 


Rewrite ' s a URL using Httpcontext.rewriteurl ().


        /// 


///the HttpContext object to rewrite the URL to.


///Redirect or rewrite path.


///the URL to rewrite.


public static void Rewriteurl (HttpContext context, string Sendtourl,


bool Isredirect)


        {


string x, y;


Rewriteurl (context, Sendtourl, Isredirect, out X, out y);


        }





        /// 


///Rewrite ' s a URL using Httpcontext.rewriteurl ().


        /// 


///the HttpContext object to rewrite the URL to.


///the URL to rewrite.


///Redirect or rewrite path.


Returns the value of Sendtourl stripped of the querystring.


///Returns The physical file path to the requested page.


public static void Rewriteurl (HttpContext context, string Sendtourl,


bool Isredirect, out string sendtourllessqstring, out string filePath)


        {


//If we need to add any extra querystring information


if (context. Request.QueryString.Count > 0)


            {


if (Sendtourl.indexof ('? ')!=-1)


Sendtourl + + "&" + context. Request.QueryString.ToString ();


Else


Sendtourl + + context. Request.QueryString.ToString ();


}





//The QueryString, if any


string querystring = String.Empty;


sendtourllessqstring = Sendtourl;


if (Sendtourl.indexof ('? ') > 0)


            {


sendtourllessqstring = sendtourl.substring (0, Sendtourl.indexof ('? '));


QueryString = sendtourl.substring (Sendtourl.indexof ('? ') + 1);


            }





//Grab the file ' s physical path


FilePath = string. Empty;


FilePath = context. Server.MapPath (sendtourllessqstring);





if (isredirect)


            {


REDIRECT The path


context. Response.Redirect ("~/" + sendtourllessqstring);


            }


Else


            {


//Rewrite the path


context. RewritePath ("~/" + sendtourllessqstring,


String.Empty, querystring);


}





//note! The adjective rewritepath () overload is only


keyword in the. NET Framework 1.1


//If you have are using the. NET Framework 1.0, use the below form instead:


//context. RewritePath (Sendtourl);


        }





        /// 


Converts a URL into one it usable on the requesting client.


        /// 


///converts ~ to the requesting creator path. Mimics the behavior of the


///Control.resolveurl () method, abound are often used by the control developers.


///the creator path.
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.