Introduction to. text urlRewrite

Source: Internet
Author: User
Author: floerggyyWww.ASPCool.comTime: 05:24:05 views:1591

1. highlights:
The first time I got dottext, I began to think it was strange that

1. After being registered with floerggyy, you can use URL: http://x.x.x.x/floerggyyto access the blogstore in the region.
(In fact, I forgot to download a page that I used to do before. aspx is just a virtual page that handles HttpHandler. It may be that I forgot to read these basic knowledge in. Text)

2. You can use the UserName as the unique identifier of the user, but the table does not find anything that is the unique constraint of the UserName. (It is still unclear where the database is set, for more information, see)
Later, we had to re-register the same user name to view the thrown exception information and confirm that there is a UserName as the only constraint.
Alas, I don't know anything about the database.



... Later I decided to write an article about URL rewriting. Later I saw that the original author of dottext briefly introduced urlRewrite, so I gave up this idea.
Later, some friends asked dottext about the URL.

2. WebConfig. config

Custom configuration section content:
<ConfigSections>
<Section name = "BlogConfigurationSettings" type = "Dottext. Framework. Util. XmlSerializerSectionHandler, Dottext. Framework"/>
<Section name = "HandlerConfiguration" type = "Dottext. Framework. Util. XmlSerializerSectionHandler, Dottext. Framework"/>
<Section name = "SearchConfiguration" type = "Dottext. Framework. Util. XmlSerializerSectionHandler, Dottext. Framework"/>
<Section name = "microsoft. web. services "type =" Microsoft. web. services. configuration. webServicesConfiguration, Microsoft. web. services, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35 "/>
<Section name = "codeHighlighter" type = "ActiproSoftware. CodeHighlighter. CodeHighlighterConfigurationSectionHandler, ActiproSoftware. CodeHighlighter"/>
</ConfigSections>

HttpHandler configuration content:
<HttpHandlers>
<Add verb = "*" path = "*. asmx "type =" System. web. services. protocols. webServiceHandlerFactory, System. web. services, Version = 1.0.5000.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a"
Validate = "false"/>
<Add verb = "*" path = "Error. aspx" type = "System. Web. UI. PageHandlerFactory"/>
<Add verb = "*" path = "*" type = "Dottext. Common. UrlManager. UrlReWriteHandlerFactory, Dottext. Common"/>
</HttpHandlers>

HttpModule configuration content:
<HttpModules>
<Add name = "UrlReWriteModule" type = "Dottext. Common. UrlManager. UrlReWriteModule, Dottext. Common"/>
<Add name = "EventHttpModule" type = "Dottext. Framework. ScheduledEvents. EventHttpModule, Dottext. Framework"/>
</HttpModules>



When you see a strange project, first open its configuration file. This is my habit :)
Let's take a look at some important configuration content:

After reading the above content in Web. config, a friend familiar with the asp.net operating mechanism will understand the running sequence of DotText code. Here I will simply repeat it.
The internal operation mechanism of aspnet (if you are not familiar with it, please refer to the <ASP. NET FameWork deep Adventure> book, which is very helpful for asp.net developers ):
Remote client Request ----> IIS ----> aspnet_isapi.dll --> aspnet_wp.exe --> HttpRuntime --->
HttpModule ---> HttpHandler Factory ---> HttpHandler. ProcessRequest () --> Response client Request
Well, the question is correct. The client Request is first intercepted by the HttpModule. When we request the URL of. text: http://www.cnblogs.com/floerggyy/, first
Dottext. Common. UrlManager is called for the UrlReWriteModule class in the namespace.
(Why is the remote request intercepted by the UrlReWriteModule? Didn't the content in the above HttpModule configuration section be marked ??? Pai_^
If this is the case, will the EventHttpModule of the Dottext. Framework. ScheduledEvents namespace intercept remote requests? When will it be intercepted?
Of course, it is in the order of first come and then, and the excellent traditions of China are forgotten !!!
(In fact, this is not very accurate. The two httpmodules are executed in order, but they are cross-running in some events in the HttpModule. The EventHttpModule class is better.
We will not analyze the code below within the scope of our theory. If you do not understand this piece, you 'd better go to the book recommended above. ^_^)

3. URL rewriting and part of code analysis (This section involves the comprehensive application of many custom configuration sections, HttpModule, and HttpHandler, so it is still a little troublesome to straighten out. It is necessary to have a little patience to analyze others' code. I personally think)

UrlReWriteModule-like Method


Private void context_BeginRequest (object sender, EventArgs e ){
// It is mainly used to set whether to rewrite the URL requested by the customer based on the request matching regular expression (it is a rewrite URL by default). Pay attention to this Code UrlHelper. setEnableUrlReWriting (context, false );
If (ConfigProvider. Instance (). IsAggregateSite ){
HttpContext context = (HttpApplication) sender). Context;

String path = context. Request. Path. ToLower ();
Int iExtraStuff = path. IndexOf (". aspx ");
If (iExtraStuff>-1 | path. IndexOf (".") =-1 ){
If (iExtraStuff>-1)
{
Path = path. Remove (iExtraStuff + 5, path. Length-(iExtraStuff + 5 ));
}

Path = regexApplication. Replace (path, string. Empty, 1, 0 );

If (path = "" | path = "/" | regexPath. IsMatch (path ))
{
UrlHelper. SetEnableUrlReWriting (context, false );
}

} Else if (context. request. path. toLower (). indexOf ("services")> 0 & context. request. path. toLower (). indexOf (". asmx ")> 0)
{
If (AlllowService (context ))
{
If (context. Request. RequestType! = "POST ")
{
String regexstr = @ "/\ w +/services /";
String url = Regex. Replace (context. Request. RawUrl, regexstr, "/services/", RegexOptions. IgnoreCase );
Context. RewritePath (url );
}
// String fileName = context. Request; // System. IO. Path. GetFileName (context. Request. Path );
// Context. RewritePath ("~ /Services/"+ fileName );
} Else {
Context. Response. Clear ();
Context. Response. End ();
}
}

}



After the HttpModule completes processing (This statement is incorrect here), go to the HttpHandler Factory. Based on the configuration content of HttpHandler, we can immediately find this class.
UrlReWriteHandlerFactory is the core of processing rewrite URL requests. Here I will analyze it in detail.
It implements IHttpHandlerFactory
(This class is very important when you look at the annotations)


After the HttpModule completes processing (This statement is incorrect here), go to the HttpHandler Factory. Based on the configuration content of HttpHandler, we can immediately find this class.
UrlReWriteHandlerFactory is the core of processing rewrite URL requests. Here I will analyze it in detail.
It implements IHttpHandlerFactory
(This class is very important when you look at the annotations)

Using System;
Using System. Web;
Using System. Web. UI;
Using System. Text. RegularExpressions;

Using Dottext. Framework;
Using Dottext. Framework. Components;
Using Dottext. Framework. Configuration;

Namespace Dottext. Common. UrlManager
{
/** // <Summary>
/// Class responisble for figuring out which. Text page to load. By default will load an array of Dottext. UrlManager. HttpHanlder
/// From the blog. config file. This contains a list of Regex patterns to match the current request to. It also allows caching of
/// Regex's and Types
/// </Summary>
Public class UrlReWriteHandlerFactory: IHttpHandlerFactory
{
Public UrlReWriteHandlerFactory () {}// Nothing to do in the cnstr
// Customize virtual METHODS Construct Httphandler during deserialization from the custom configuration section content
Protected virtual HttpHandler [] GetHttpHandlers (HttpContext context)
{
Return HandlerConfiguration. Instance (). HttpHandlers;
}

/** // <Summary>
/// Implementation of IHttpHandlerFactory. By default, it will load an array of HttpHanlder (Dottext. UrlManager. HttpHandler) from
/// The blog. config. This can be changed, by overrideing the GetHttpHandlers (HttpContext context) method.
/// </Summary>
/// <Param name = "context"> Current HttpContext </param>
/// <Param name = "requestType"> Request Type (Passed along to other IHttpHandlerFactory's) </param>
/// <Param name = "url"> The current requested url. (Passed along to other IHttpHandlerFactory's) </param>
/// <Param name = "path"> The physical path of the current request. Is not gaurenteed to exist (Passed along to other IHttpHandlerFactory's) </param>
/// <Returns>
/// Returns an Instance of IHttpHandler either by loading an instance of IHttpHandler or by returning an other
/// IHttpHandlerFactory. GetHanlder (HttpContext context, string requestType, string url, string path) method
/// </Returns>
// Implementation interface IHttpHandlerFactory defined method
Public virtual IHttpHandler GetHandler (HttpContext context, string requestType, string url, string path)
{
// Get the Handlers to process. By defualt, we grab them from the blog. config
HttpHandler [] items = GetHttpHandlers (context );
// Dottext. Framework. Logger. LogManager. Log ("path", Dottext. Framework. Util. Globals. RemoveAppFromPath (context. Request. Path, context. Request. ApplicationPath ));
// Do we have any?
If (items! = Null)
{
Int count = items. Length;

For (int I = 0; I <count; I ++)
{
// We shocould use our own cached Regex. This shocould limit the number of Regex's created
// And allows us to take advantage of RegexOptons. Compiled
// Match the request types defined in the configuration section one by one
If (items [I]. IsMatch (Dottext. Framework. Util. Globals. RemoveAppFromPath (context. Request. Path, context. Request. ApplicationPath )))
{
// Note that the returned Httphandler instance is critical.
// Throw new Exception ();
Switch (items [I]. HandlerType)
{
Case HandlerType. Page: // The default value is Page.

Return ProccessHandlerTypePage (items [I], context, requestType, url );
Case HandlerType. Direct:
HandlerConfiguration. SetControls (context, items [I]. BlogControls );
Return (IHttpHandler) items [I]. Instance ();
Case HandlerType. Factory:
// Pass a long the request to a custom IHttpHandlerFactory
Return (IHttpHandlerFactory) items [I]. Instance (). GetHandler (context, requestType, url, path );
Default:
Throw new Exception ("Invalid HandlerType: Unknown ");
}
}
}
}
// If we do not find the page, just let ASP. NET take over
Return PageHandlerFactory. GetHandler (context, requestType, url, path );
}


Private IHttpHandler ProccessHandlerTypePage (HttpHandler item, HttpContext context, string requestType, string url)
{
String pagepath = item. FullPageLocation;
If (pagepath = null)
{
Pagepath = HandlerConfiguration. Instance (). FullPageLocation;
}
HandlerConfiguration. SetControls (context, item. BlogControls );
IHttpHandler myhandler = PageParser. GetCompiledPageInstance (url, pagepath, context );
Return myhandler;
}


Public virtual void ReleaseHandler (IHttpHandler handler)
{

}
}
}

Note how it combines the content in the custom configuration section into the httphandler instance.
After straighten out the above, it is not difficult to rewrite the url for understanding. text ....

If you have any understanding of the above, you are welcome to correct it.

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.