由于其保护级别,’System.Exception.HResult’无法访问
我在我的代码中收到以下错误。
编译器错误消息:CS0122:由于其保护级别,’System.Exception.HResult’无法访问
我的App_Code
文件夹中有一个类,并使用LogException()
方法将exception详细信息插入到数据库中。
业务访问层引用已经提供给此类以访问function。
我在我的本地机器和本地IIS中尝试了它,它工作正常。 但是当我在Windows服务器IIS上托管它时,它给了我错误。
请帮我解决这个问题。
更新:
下面是我在App_Code/Exception.cs
类中的函数,我在这个类中引用了业务访问层。
public static void LogException(Exception ex, string userId, string refPage, string appName) { try { ExceptionManager objEx = new ExceptionManager(); // this is business class objEx.InsertErrorLog(userId, appName, ex.HResult, ex.GetHashCode(), ex.GetType().ToString(), ex.Message, ex.Source, ex.StackTrace, refPage); } catch { DestroySession(); } }
听起来你正试图设置Exception
的HResult
属性。 你不能这样做,因为它的setter 受到保护 。 如果您需要设置此属性,那么您唯一的选择是派生一种新类型的Exception
例如
public class CustomException : Exception { public CustomException(string message, int hresult) : base(message) { HResult = hresult } }
在我看来,您的实际问题是您的开发/部署环境之间的.NET版本的差异。 HResult
财产完全 protected
,直到4.5。 我认为,您在部署之后看到这个原因的原因是因为您在较旧版本的.NET下运行。
您需要在部署计算机上安装.NET 4.5。
更新到.NET 4.5。
或者调用System.Runtime.InteropServices.Marshal.GetHRForException 。
来自原始post的代码,具有此更改:
public static void LogException(Exception ex, string userId, string refPage, string appName) { try { ExceptionManager objEx = new ExceptionManager(); // this is business class objEx.InsertErrorLog(userId, appName, System.Runtime.InteropServices.Marshal.GetHRForException(ex), ex.GetHashCode(), ex.GetType().ToString(), ex.Message, ex.Source, ex.StackTrace, refPage); } catch { DestroySession(); } }