2011-01-09 71 views
0

我想創建網址與網頁強類型對象的路由,但我不斷收到第一行空的對象,所以它崩潰網址與強類型對象路由

//Getting the suitable executing Page 
var display = BuildManager.CreateInstanceFromVirtualPath(_virtualPath,typeof(Page)) as IProfileHandler; 
//Setting Page Parameters 
display.MemberId = Convert.ToInt32(requestContext.RouteData.Values["ID"]); 
//Return Page 
return display; 

public interface IProfileHandler : IHttpHandler 
{ 
    int MemberId 
    { 
     get; 
     set; 
    } 
} 
+0

哪個對象爲空?顯示或requestContext?如果它是顯示的,當你調試的時候,構建管理器返回一個對象,但它不是IProfileHandler類型的? – Vadim 2011-01-09 16:55:12

+0

display is null,當我投射到iprofilehandler時它返回null,當我投射到ihttphandler時它返回指定的對象 – user510336 2011-01-09 17:16:59

回答

1

對於那些誰路過這裏一個web.config入口,這裏是我做什麼,我增加一些屬性到我的網頁類和我鑄造那個班,這似乎是個好主意。

0

CreateInstanceFromVirtualPath沒有返回一個對象,實施IProfileHandler

編輯:

你試圖返回的對象強制轉換爲IProfileHandler。這意味着你說「Ok編譯器,我知道這個方法返回一個object,但我保證它已經是一個實現IProfileHandler的實例。」由於CreateInstanceFromVirtualPath方法是在不知道自定義類的情況下創建的,因此無法返回保證遵循由您的自定義界面設置的合約(具有屬性int MemberId)的對象。由於對象不能正確鑄造,並且您正在使用運算符,所以您將得到空值。如果你做了一個正常的演員,一個InvalidCastException會被拋出。

我不確定我是否是合適的人來回答你如何實現它,因爲我從來沒有使用HttpHandlers做過任何工作,但根據this documentation看起來你會創建一個實現它的類IHttpHandler,修改你的web.config使用新的處理程序,然後將其轉換爲新的類。也許像

public class ProfileHttpHandler: IHttpHandler 
{ 
    public int MemberId { get; set; } 

    public bool IsReusable 
    { 
     get 
     { 
      // return value here 
     } 
    } 

    public void ProcessRequest(HttpContext context) 
    { 
     // custom request processing here 
    } 
} 

<configuration> 
    <system.web> 
     <httpHandlers> 
     <add verb="*" path="*.yourIntendedExtension" type="FQN, Assembly" /> 
     </httpHandlers> 
    </system.web> 
</configuration>