Asp.net
從自定義處理程序呼叫預設的 asp.net HttpHandler
我正在將 ASP.NET 路由添加到較舊的 webforms 應用程序。我正在使用自定義
HttpHandler來處理所有內容。在某些情況下,我想將特定路徑映射回aspx文件,因此我只需將控制權傳遞回 asp.net 的預設 HttpHandler。我得到的最接近的是這個
public void ProcessRequest(HttpContext context) { // .. when we decide to pass it on var handler = new System.Web.UI.Page(); handler.ProcessRequest(context); MemoryStream steam = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); HtmlTextWriter htmlWriter = new HtmlTextWriter(writer); handler.RenderControl(htmlWriter); // write headers, etc. & send stream to Response }它什麼都不做,沒有任何輸出到流中。MS 的 System.Web.UI.Page(作為 IHttpHandler)的文件說“不要呼叫 ProcessRequest 方法。它是供內部使用的”。
環顧四周,您似乎可以使用 MVC 執行此操作,例如:MvcHttpHandler 似乎沒有實現 IHttpHandler
還有一個東西
System.Web.UI.PageHandlerFactory看起來它只會為 aspx 文件生成一個頁面處理程序,但它是內部的,我不能直接使用它。此頁面: http: //msdn.microsoft.com/en-us/library/bb398986.aspx指的是“預設的 asp.net 處理程序”,但沒有標識一個類或給出任何指示如何使用它。
關於如何做到這一點的任何想法?是否可以?
堅持有回報!這實際上有效,而且由於這些資訊似乎幾乎無處可用,我想我會回答我自己的問題。感謝 Robert 的這篇關於使用內部建構子實例化事物的文章,這是關鍵。
http://www.rvenables.com/2009/08/instantiating-classes-with-internal-constructors/
public void ProcessRequest(HttpContext context) { // the internal constructor doesn't do anything but prevent you from instantiating // the factory, so we can skip it. PageHandlerFactory factory = (PageHandlerFactory)System.Runtime.Serialization.FormatterServices .GetUninitializedObject(typeof(System.Web.UI.PageHandlerFactory)); string newTarget = "default.aspx"; string newQueryString = // whatever you want string oldQueryString = context.Request.QueryString.ToString(); string queryString = newQueryString + oldQueryString!="" ? "&" + newQueryString : ""; // the 3rd parameter must be just the file name. // the 4th parameter should be the physical path to the file, though it also // works fine if you pass an empty string - perhaps that's only to override // the usual presentation based on the path? var handler = factory.GetHandler(context, "GET",newTarget, context.Request.MapPath(context,newTarget)); // Update the context object as it should appear to your page/app, and // assign your new handler. context.RewritePath(newTarget , "", queryString); context.Handler = handler; // .. and done handler.ProcessRequest(context); }…就像一些小奇蹟一樣,aspx 頁面處理和呈現完全在程序內,無需重定向。
我希望這只會在 IIS7 中工作。