简体   繁体   中英

How can I get the relative URL of a page from an instance of the page object itself

Given an instance of a class that derives from System.Web.Page (ie. a normal page instance) how can I get the relative URL required to request that page (without a Request object).

To clarify, I'm instanciating a Page derived class outside of the normal page request pipeline.

eg

var p = new MyPage();
// p.Request is not going to be valid

From that how can I get the appropriate URL that would normally be used to request the page?

Short answer - you can't, because you're coming at it backwards. Without a Request to look at, the "request path" has no meaning.

A Page object has no idea of the paths that will cause it to be called. In fact, it's just a .net class that implements IHttpHandler to generate output.

When a request for a .aspx page comes in, IIS hands it off to the asp.net pipleline. The asp.net engine determines the proper handler based on the path. In this case, it's System.Web.UI.PageHandlerFactory. This class uses the request path to figure out the correct Page object to instantiate. It does this by looking at the request path, and using that to compile the .aspx into .net code and then instantiate the class that compilation results in.

Also unfortunately for your case, the PageHandlerFactory (actually the supporting class BuildManager) allow you to find the information you want in only one direction - virtual path to compiled class. This makes sense because multiple paths could (in theory) map to a single Page.

Check out the any articles on the asp.net request pipeline for more information, or look into the PageHandlerFactory or BuildManager classes in System.Web.

System.Web.Page具有对派生类可见的Request属性。

试试Request.VirtualPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM