简体   繁体   English

IIS ASP.NET 4.0的异常并在私有字段上使用反射

[英]Exception with IIS ASP.NET 4.0 and using reflection on private field

We are having a problem with the following code when hosted in IIS running asp.net 4: 在运行asp.net 4的IIS中托管时,我们遇到以下代码问题:

        DataTable dt = new DataTable();
        FieldInfo TableCaseSensitiveAmbientFieldInfo =
            typeof(DataTable).GetField("_caseSensitiveUserSet", BindingFlags.Instance | BindingFlags.NonPublic);
        TableCaseSensitiveAmbientFieldInfo.SetValue(dt, true);

The .SetValue() call fails with a FieldAccessException (this code is from a public source code file name ADONetHelper.cs which is used from a public source dll named CompactFormatterPlus) .SetValue()调用失败并出现FieldAccessException(此代码来自公共源代码文件名ADONetHelper.cs,它使用名为CompactFormatterPlus的公共源dll)

This seems to only happen when hosted in IIS. 这似乎只发生在IIS中托管时。

We believe it is due to a reflection/code access permission (after searching for an answer) but we have not found the right set of values to enable this code to work. 我们认为这是由于反射/代码访问权限(在搜索答案之后),但我们没有找到正确的值集来启用此代码。

Any thoughts ?? 有什么想法吗 ?? Thanks, Fred 谢谢,弗雷德

By default in IIS 7.0 applications are running in "medium trust". 默认情况下,IIS 7.0中的应用程序以“中等信任”运行。 And ReflectionPermission is disabled by default with Medium Trust. 默认情况下,使用中等信任禁用ReflectionPermission。

Medium Trust Summary 中等信任摘要

The main constraints placed on medium trust Web applications are: ... ReflectionPermission is not available. 对中等信任Web应用程序的主要限制是:... ReflectionPermission不可用。 This means you cannot use reflection. 这意味着你不能使用反射。

But seems like DataTable.CaseSensitive Property has a getter and a setter. 但似乎DataTable.CaseSensitive Property有一个getter和一个setter。 I recoment that you keep away of reflection if at all possible. 我重申,如果可能的话,你要远离反射。 For example when you upgrade in future to another .NET framework that private method could be gone and your app will break. 例如,当您将来升级到另一个.NET框架时,私有方法可能会消失,您的应用程序将会中断。

If you are (de)serializing the DataSet and maybe a better idea would be to "manually" change "caseSensitiveAmbient" part in serialized XML. 如果您(de)序列化DataSet,可能更好的想法是“手动”更改序列化XML中的“caseSensitiveAmbient”部分。

Reflecting private members only works when the code runs under full trust. 只有当代码在完全信任下运行时,才能反映私有成员。 ASP .NET by default runs in medium trust. 默认情况下,ASP .NET以中等信任方式运行。

Therefore, you need to configure your application to run in full trust for this to work. 因此,您需要将应用程序配置为完全信任,以使其正常工作。

How to do this is explained in this ASP .NET Trust Levels article, but basically you must add your assembly to the <fullTrustAssemblies> list under the <securityPolicy> element in web.config. ASP .NET Trust Levels文章中解释了如何执行此操作,但基本上您必须将程序集添加到web.config中<securityPolicy>元素下的<securityPolicy> <fullTrustAssemblies>列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM