Get current System.Web.UI.Page from HttpContext?
这实际上是一个两部分的问题。 首先,HttpContext.Current是否对应于当前的System.UI.Page对象?
第二个问题(可能与第一个问题有关)是为什么我不能使用以下内容查看当前页面是否实现了接口:
1 2 3 4 5 6 7 8 | private IWebBase FindWebBase() { if (HttpContext.Current as IWebBase != null) { return (IWebBase)HttpContext.Current.; } throw new NotImplementedException("Crawling for IWebBase not implemented yet"); } |
一般情况是某些控件需要知道它们是作为SharePoint Webpart还是作为Asp.Net框架的一部分执行的。
我已经通过要求控件传递对自身的引用并检查控件的Page属性来解决该问题,但是我仍然很好奇为什么上述方法不起作用。
编译器错误是:
无法通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换将System.Web.HttpContext转换为... IWebBase。
否,从MSDN的HttpContext.Current上获取:"获取或设置当前HTTP请求的HttpContext对象。"
换句话说,它是HttpContext对象,而不是Page。
您可以使用以下方法通过HttpContext到达Page对象:
1 2 3 4 5 6 | Page page = HttpContext.Current.Handler as Page; if (page != null) { // Use page instance. } |
您正在寻找
如果需要当前正在执行的精确页面,则可能需要使用
请看我的回答:
为什么HttpContext.Current.Handler为null?
也许可以解决您的问题。