从 HttpContext 获取当前 System. Web.UI.Page?

这实际上是一个两部分的问题。首先,HttpContext. Current 是否对应于当前 System.UI.Page 对象?

第二个问题,可能和第一个问题有关,为什么我不能使用下面的方法来查看当前页面是否实现了一个接口:

private IWebBase FindWebBase()
{
if (HttpContext.Current as IWebBase != null)
{
return (IWebBase)HttpContext.Current.;
}
throw new NotImplementedException("Crawling for IWebBase not implemented yet");
}

一般情况下,有些控件需要知道它们是作为 SharePoint Web 部件执行,还是作为 Asp 的一部分执行。网络架构。

我已经通过要求控件传递对其自身的引用并检查控件的 Page 属性来解决这个问题,但是我仍然很好奇为什么上述方法不起作用。

编译器错误是: 无法转换系统。韦伯。通过引用转换、装箱转换、取消装箱转换、包装转换或空类型转换将 HttpContext 转换为... IWebBase。

93434 次浏览

You're looking for HttpContext.Handler. Since Page implements IHttpHandler, you'll obtain a reference to the currently executing page.You'll have to cast it, or at least try to cast it to the particular type you're looking for.

HttpContext.Current simply returns the singleton instance of HttpContext. Therefore, it is not and can never be, a page.

No, from MSDN on HttpContext.Current: "Gets or sets the HttpContext object for the current HTTP request."

In other words it is an HttpContext object, not a Page.

You can get to the Page object via HttpContext using:

Page page = HttpContext.Current.Handler as Page;


if (page != null)
{
// Use page instance.
}

You may want to use HttpContext.Current.CurrentHandler if you want the precise page that is currently executing. For example, a request for Default.aspx is sent, but an error is thrown and you do a Response.Transfer to your custom ErrorHandler.aspx page. CurrentHandler will return the instance of ErrorHandler.aspx (if called after the error) whereas HttpContext.Current.Handler would return an instance of Default.aspx.

Please see my answer :
Why HttpContext.Current.Handler is null?

Maybe resolved your problem.