问题
I am trying to create url routing with strongly typed objects for pages but I keep getting null object on the first line so it's crashing
//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;
}
}
回答1:
for those who pass by here , here is what I did , i added few properties to my page class and I am casting to that class , which seems good and nice idea.
回答2:
CreateInstanceFromVirtualPath
isn't returning an object that implements IProfileHandler
.
Edit:
You're trying to cast the return object to an IProfileHandler
. That means you're saying "Ok Compiler, I know this method returns an object
, but I promise it's already an instance that implements IProfileHandler
." Since the CreateInstanceFromVirtualPath
method was created without the knowledge of your custom class, it has no way to return an object that is guaranteed to follow the contract set by your custom interface (have a property int MemberId
). Because the object can't be casted properly and you are using the as
operator, you are getting null. Had you done a normal cast, an InvalidCastException
would have been thrown.
I'm not sure if I'm the appropriate person to answer how you'd implement it since I've never done any work with HttpHandlers, but according to this documentation it looks like you'd create a class that implements IHttpHandler, modify your web.config to use the new handler and then cast it to your new class. Maybe something like
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
}
}
with a web.config entry of
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.yourIntendedExtension" type="FQN, Assembly" />
</httpHandlers>
</system.web>
</configuration>
来源:https://stackoverflow.com/questions/4640344/url-routing-with-strongly-typed-objects