Access to the registry key is denied

Access to the registry key is denied

描述:在执行当前的web请求时,发生了一个未处理的异常。请检查堆栈跟踪(stack trace)以获取关于此错误的更多信息以及哪行代码引起的。

异常详情:System.UnauthorizedAccessException: 拒绝访问注册表键。ASP.NET进程没有获得访问此资源的授权。

概述:默认情况下,ASP.NET 2.0 Web应用程序和Web服务的信任级别为Full。它在Web.config文件中指定,位于<system.web>节点下。

<trust level="[Full|High|Medium|Low|Minimal]" />

Full级别赋予了无限制的特权,因此在web应用程序中可以对文件,注册表,Windows事件日志等进行操作。

前些天,在编写Web应用程序时,某项功能需要修改注册表。奇怪的是在VS 2005 内置的web服务器中,程序运行正常;部署到本机,使用http://localhost/...访问一切也是正常;但是使用http://hostname/或者部署到其它计算机时却出现了拒绝访问注册表异常。后来google一番,发现可能是<trust>的级别设置的问题,将level设置为Full,一切正常。可是根据Hosting ASP.NET Applications in Medium Trust(By Scott Mitchell)中的描述“默认情况下,ASP.NET 2.0 Web应用程序和Web服务的信任级别为Full”,这不是很奇怪吗?于是我又去掉了<trust level=”Full” />,再次试验,可是这次访问访问注册表又正常了,没有异常抛出

后记:最近项目快要做完了,于是有了想把在项目过程中遇到的问题以及解决方法记录下来,供后来参考。无奈只是大概记得当初出现了这么一个错误以及解决方法,有些却记不得了。因此下次遇到问题时一定要详细的记录,问题描述,出现时的context,以及解决方法。

另外附上两篇关于ASP.NET2.0中关于trust的文章,希望对遇到类似问题的朋友有所帮助。


How To: Use Medium Trust in ASP.NET 2.0

 

patterns & practices Developer Center

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Microsoft Corporation

August 2005

Applies To

  • ASP.NET version 2.0

Summary

This How To shows you how to configure ASP.NET Web applications to run in medium trust. If you host multiple applications on the same server, you can use code access security and the medium trust level to provide application isolation. By setting and locking the trust level in the machine-level Web.config file, you can establish security policies for all Web applications on the server. Running at medium trust with ASP.NET version 2.0 is easier than with ASP.NET version 1.1 because when using ASP.NET 2.0, you have access to Microsoft SQL Server databases at medium trust. Medium trust still provides a constrained environment for isolating applications from one another and from shared server resources. Medium trust applications have no registry access, no event log access, and no ability to use reflection. Web access is limited to the network address that you define in the <<trust/>> element, and file system access is limited to the application's virtual directory hierarchy. If medium trust policy is too restrictive, you can create and use a custom policy file.

Contents

Objectives
Overview
What's New in 2.0
Medium Trust Summary
Summary of Steps
Step 1. Configure Medium Trust
Step 2. Lock the Trust Level
Step 3. Optionally Create a Custom Policy Based on Medium Trust
OleDbPermission, EventLogPermission and FileIOPermission
Developing for Medium Trust
Additional Resources

Objectives

  • Learn how to develop Web applications using medium trust.
  • Learn what has changed with partial trust Web applications in ASP.NET version 2.0.
  • Learn about the constraints while using medium trust levels.
  • Configure medium trust levels in your Web application.
  • Modify trust levels to create your own custom trust levels.

Overview

By default, ASP.NET 2.0 Web applications and Web services run with full trust and applications can perform privileged operations and access resources subject only to operating system security and Windows access control lists (ACLs).

To lock down an ASP.NET application and to provide an additional level of application isolation in a hosted environment, you can use code access security to restrict the resources the application can access and the privileged operations it can perform. You do this by configuring the <trust> element as shown here.

Copy Code

<trust level="Full|High|Medium|Low|Minimal" />

 

The <trust> element supports a number of default trust levels. Each level in succession provides a more restrictive environment (with fewer code access security permissions) in which to run your application.

Internet service providers (ISPs) that need to host multiple applications from many different companies frequently use the medium trust level to help ensure that applications cannot read each other's data or interfere with one another in any way. Medium trust also places restrictions on the types of shared system resources that the applications can access.

What's New in 2.0

The main differences between ASP.NET version 1.1 and ASP.NET version 2.0 for the trust levels are the following:

  • In ASP.NET versions 1.1 and 2.0, medium trust applications can access SQL Server databases because the SQL Server managed data provider does not demand full trust and SqlClientPermission is granted to medium trust applications.
  • In .NET Framework version 2.0, the Oracle .NET data provider, the OLE DB .NET data provider, and the ODBC .NET data provider no longer demand full trust. This allows you to access SQL Server and other databases from partial trust applications. To use these providers from medium trust applications in ASP.NET, you need to customize policy and grant the appropriate permission: for example, OraclePermission, OleDbPermission or OdbcPermission.
  • In ASP.NET version 2.0, SmtpPermission is available at full, high, and medium trust levels. This allows applications to send e-mail.
  • In ASP.NET version 1.1, you had to grant code full trust to access the event log. This is no longer required in ASP.NET version 2.0, although you must still create a custom trust policy file to grant the EventLogPermission, as described later in this document.

Medium Trust Summary

The main constraints placed on medium trust Web applications are:

  • OleDbPermission is not available. This means you cannot use the ADO.NET managed OLE DB data provider to access databases. However, you can use the managed SQL Server provider to access SQL Server databases.
  • EventLogPermission is not available. This means you cannot access the Windows event log.
  • ReflectionPermission is not available. This means you cannot use reflection.
  • RegistryPermission is not available. This means you cannot access the registry.
  • WebPermission is restricted. This means your application can only communicate with an address or range of addresses that you define in the <trust> element.
  • FileIOPermission is restricted. This means you can only access files in your application's virtual directory hierarchy. Your application is granted Read, Write, Append, and PathDiscovery permissions for your application's virtual directory hierarchy.

You are also prevented from calling unmanaged code or from using Enterprise Services.

Summary of Steps

To use medium trust in your ASP.NET applications:

  • Step 1. Configure medium trust.
  • Step 2. Lock the trust level.
  • Step 3. Optionally create a custom policy based on medium trust.

Step 1. Configure Medium Trust

To configure an application to run with medium trust, add the following element to either the application's specific Web.config file in the application's virtual root directory or to the machine-level Web.config file.

Copy Code

<trust level="Medium" originUrl="" />

 

Note   If present, the originUrl attribute can be used by some permissions, such as WebPermission, to restrict connectivity to a defined set of addresses.

To configure all Web applications on a server to run with medium trust, add this element to the machine-level Web.config file located in the following folder: %windir%/Microsoft.NET/Framework/{version}/CONFIG.

By default, Web applications are configured to run with full trust as shown in the following default configuration from the machine-level Web.config file.

Copy Code

<location allowOverride="true">

 <system.web>

   <securityPolicy>

     <trustLevel name="Full" policyFile="internal" />

     <trustLevel name="High" policyFile="web_hightrust.config" />

     <trustLevel name="Medium"

                 policyFile="web_mediumtrust.config" />

     <trustLevel name="Low"  policyFile="web_lowtrust.config" />

     <trustLevel name="Minimal"

                 policyFile="web_minimaltrust.config" /> 

   </securityPolicy>

   <trust level="Full" originUrl="" />

 </system.web>

</location>

 

To review the full set of permissions available to medium trust applications, view the Web_mediumtrust.config file.

Step 2. Lock the Trust Level

Application service providers or anyone responsible for running multiple Web applications on the same server should apply the medium trust policy setting in the machine-level Web.config file and then lock the trust level for all Web applications.

To do this, set the allowOverride attribute to false in the machine-level Web.config file, as shown in the following code example.

Copy Code

<location allowOverride="false">

 <system.web>

   <securityPolicy>

     <trustLevel name="Full" policyFile="internal" />

     <trustLevel name="High" policyFile="web_hightrust.config" />

     <trustLevel name="Medium"

                 policyFile="web_mediumtrust.config" />

     <trustLevel name="Low" 

                 policyFile="web_lowtrust.config" />

     <trustLevel name="Minimal"

                 policyFile="web_minimaltrust.config" /> 

   </securityPolicy>

   <trust level="Medium" originUrl="" />

 </system.web>

</location>

 

By setting allowOverride="false", an individual developer is unable to override the medium trust policy setting in their application's Web.config file.

Step 3. Optionally Create a Custom Policy Based on Medium Trust

If medium trust proves too restrictive, you can create a custom policy file based on the medium trust policy. For example, you might want to allow applications to do one of the following: connect to an Oracle database, write events to the Windows event log, or read files from a specified directory outside of the application's virtual directory hierarchy.

To create a custom policy based on medium trust

1.                 Copy the medium trust policy file web_MediumTrust.config located in the following directory to create a new policy file in the same directory: %windir%/Microsoft.NET/Framework/{Version}/CONFIG.

Give it a name that indicates that it is your variation of medium trust; for example, it could be named customWeb_MediumTrust.config.

2.                 Add the permissions that you want to grant. In the following example, the FileIOPermission is modified to allow read access to a specific directory outside of the application's virtual directory hierarchy.

Copy Code

<PermissionSet

    class="NamedPermissionSet"

    version="1"

    Name="ASP.Net">

  ...

    <IPermission

         class="FileIOPermission"

       version="1"

         Read="C:/SomeDir;$AppDir$"

         Write="$AppDir$"

         Append="$AppDir$"

         PathDiscovery="$AppDir$"

/>

  ...

</PermissionSet>

 

3.                 Create a new custom policy level in your machine-level Web.config file. The policy file is the name of the policy file you created in step 1.

Copy Code

<securityPolicy>

  <trustLevel name="CustomMedium"

              policyFile="customWeb_mediumtrust.config" />

  ...

</securityPolicy>

 

4.                 Configure applications to run at the new custom policy level by setting the trust level to "CustomMedium". Your security policy will resemble the following example.

Copy Code

<system.web>

  <securityPolicy>

   <trustLevel name="CustomMedium"

               policyFile="customWeb_mediumtrust.config" />

   <trustLevel name="Full" policyFile="internal" />

   <trustLevel name="High"

               policyFile="web_hightrust.config" />

   <trustLevel name="Medium"

               policyFile="web_mediumtrust.config" />

   <trustLevel name="Low"  policyFile="web_lowtrust.config" />

   <trustLevel name="Minimal"

               policyFile="web_minimaltrust.config" />

 </securityPolicy>

 <trust level="CustomMedium" originUrl="" />

</system.web>

 

OleDbPermission, EventLogPermission and FileIOPermission

Common permissions that you might need to add include:

  • OleDbPermission
  • EventLogPermision
  • FileIOPermission

OleDbPermission

If you support multiple database server types, you need to grant OleDbPermission to Web applications in addition to SqlClientPermission, which is already granted by medium trust policy.

To extend medium trust policy to grant OleDbPermission

1.                 Create a custom policy file and configure your application to use the custom trust level, as described in the "Modifying Medium Trust Policy" section earlier in this document.

2.                 Add the following permission class to the <SecurityClasses> section.

Copy Code

<SecurityClass Name="OleDbPermission"

               Description="System.Data.OleDb.OleDbPermission, System.Data, Version= 2.0.0 .0,

                            Culture=neutral, PublicKeyToken=b 77a 5c 561934e089"/>

 

3.                 Add the unrestricted OleDbPermission to the "ASP.Net" named permission set, as shown in the following example.

Copy Code

<PermissionSet

    class="NamedPermissionSet"

    version="1"

    Name="ASP.Net">

  ...

     <IPermission class="OleDbPermission"

                  version="1"

                  Unrestricted="true"/>

     ...

   </PermissionSet>

 

Locking Down Connection Strings

Adding the unrestricted OleDbPermission to your policy file means that your application can use any OLE DB provider on the server. In a hosted environment, an administrator may need to use the more advanced form of the OleDbPermission syntax to lock down connection strings used with OleDbPermission to allow access only to specific databases. The following example shows how to restrict access to a specific OLE DB data source.

Copy Code

<IPermission class="OleDbPermission"

             version="1">

  <add ConnectionString=

          "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/data/w4w.mdb"

       KeyRestrictions=""

       KeyRestrictionBehavior="AllowOnly"/>

</IPermission>

 

The <add> element supports the following attributes:

  • ConnectionString. This element specifies a permitted connection string.
  • KeyRestrictions. This element specifies additional connection string parameters that may or may not be added to the connection string depending on the value of KeyRestrictionBehavior. Specify connection string parameters using the syntax parameterName=. You can specify multiple parameters by delimiting each one with a semi-colon (;).
  • KeyRestrictionBehavior. You can set this to AllowOnly or PreventUsage.

·                        If you use AllowOnly, only the additional connection string parameters specified in the KeyRestrictions attribute may be added to the connection string specified in ConnectionString.

·                        If you use PreventUsage, the connection string parameters specified in the KeyRestrictions attribute may not be added to the connection string specified in ConnectionString, although other connection string parameters may be added.

If no key restrictions are specified, and the KeyRestrictionBehavior attribute is set to AllowOnly, no additional connection string parameters are allowed.

If no key restrictions are specified, and the KeyRestrictionBehavior property is set to PreventUsage, additional connection string parameters are allowed.

EventLogPermission

Medium trust policy does not permit access to the Windows event log.

To enable access to the event log

1.                 Create a custom policy file and configure your application to use the custom trust level, as described in the "Modifying Medium Trust Policy" section earlier in this document.

2.                 Add the following permission class to the <SecurityClasses> section to the custom policy file.

Copy Code

<SecurityClasses>

  ...

  <SecurityClass Name="EventLogPermission"

                 Description="System.Diagnostics.EventLogPermission, System, Version= 2.0.0 .0,

                             Culture=neutral, PublicKeyToken=b 77a 5c 561934e089" />

  ...

</SecurityClasses>

                       

 

3.                 Add the following EventLogPermission to the "ASP.Net" named permission set.

Copy Code

<PermissionSet

    class="NamedPermissionSet"

    version="1"

    Name="ASP.Net">

  ...

     <IPermission

          class="EventLogPermission"

          version="1">

        <Machine name="."

        access="Write"/>

     </IPermission>

     ...

   </PermissionSet>

 

Note   At the time of writing, you must set access="administer" to be able to write to the event log from a partial trust application.

Creating Event Sources

If your application needs to use application specific event sources, you should create them at installation time when administrator privileges are available. A good approach is to use a .NET installer class, which can be instantiated by the Windows Installer (if you are using .msi deployment) or by the InstallUtil.exe system utility.

If you are unable to create event sources at installation time, and you are in deployment, the administrator should manually create new event source entry beneath the following registry key

Copy Code

HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Eventlog/<LogName>

Note   You should not grant write permission to the ASP.NET process account (or any impersonated account if your application uses impersonation) on the HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Eventlog/ registry key. If you allow write access to this key and the account is compromised, the attacker can modify any log-related setting, including access control to the log, for any log on the system.

FileIOPermission

If you need to allow your application to access files outside of the application's virtual directory hierarchy, you can create a custom policy file based on the medium trust file, and then modify the FileIOPermission.

For example, the following definition enables an application to read files in the "C:/SomeDir" directory.

Copy Code

<IPermission

  class="FileIOPermission"

  version="1"

  Read="C:/SomeDir;$AppDir$"

  Write="$AppDir$"

  Append="$AppDir$"

  PathDiscovery="$AppDir$"

/>

 

By letting applications access files beyond the application's virtual directory hierarchy, you diminish the ability of code access security to provide application isolation. If you have multiple applications on a single server, you need to protect resources, such as files with ACLs, and use separate identities for each application.

Developing for Medium Trust

To help design and develop your applications for medium trust, consider the following:

  • Identify the types of resources that your application needs to access and the privileged operations it needs to perform.

You need to know which code access security permissions your application requires. For more information about permission requirements, see the "Resource Access Permissions Summary" and "Privileged Operation Permissions Summary" sections in How To: Use Code Access Security in ASP.NET 2.0.

  • Know what permissions are available at medium trust.

The best way to learn what permissions are available is to open and examine the web_MediumTrust.config file in the following folder: %windir%/Microsoft.NET/Framework/{Version}/CONFIG.

  • Configure your development environment and your application's Web.config file for medium trust.

Do this at the start of development so that you can immediately see what permission requests fail and what issues need to be addressed.

  • For existing applications, consider using the Permcalc tool.

If you have an existing application that you want to run at medium trust, consider using the Permcalc tool to help you determine precisely which permissions your application needs. You should also make sure that extensive testing is performed to verify that all code paths through your application have been executed. Failure to do so can lead to unexpected security exceptions at run time.

The best approach is to target your trust level before you begin design and development work and to design and develop specifically for this trust level. Common causes of security exceptions when you switch an existing application to medium trust include:

  • Calling unmanaged code.
  • Accessing the registry.
  • Writing to the event log.
  • Connecting to databases other than SQL Server.
  • Accessing Web resources on remote servers.
  • Accessing the file system beyond your application's virtual directory hierarchy.

Additional Resources

Feedback

Provide feedback by using either a Wiki or e-mail:

We are particularly interested in feedback regarding the following:

  • Technical issues specific to recommendations
  • Usefulness and usability issues

Technical Support

Technical support for the Microsoft products and technologies referenced in this guidance is provided by Microsoft Support Services. For product support information, please visit the Microsoft Product Support Web site at http://support.microsoft.com.

Community and Newsgroups

Community support is provided in the forums and newsgroups:

To get the most benefit, find the newsgroup that corresponds to your technology or problem. For example, if you have a problem with ASP.NET security features, you would use the ASP.NET Security forum.

Contributors and Reviewers

  • External Contributors and Reviewers: Jason Taylor, Security Innovation; Rudolph Araujo, Foundstone Professional Services
  • Microsoft Consulting Services and PSS Contributors and Reviewers: Adam Semel, Tom Christian, Wade Mascia
  • Microsoft Product Group Contributors and Reviewers: Stefan Schackow
  • Test team: Larry Brader, Microsoft Corporation; Nadupalli Venkata Surya Sateesh, Infosys Technologies Ltd; Sivanthapatham Shanmugasundaram, Infosys Technologies Ltd.
  • Edit team: Nelly Delgado, Microsoft Corporation; Tina Burden McGrayne, TinaTech Inc.
  • Release Management: Sanjeev Garg, Microsoft Corporation

Hosting ASP.NET Applications in Medium Trust
By Scott Mitchell

Introduction
Many independent developers and small companies building Internet-accessible web applications turn to web hosting companies to host their website. Web hosting companies offer a variety of plans, from dedicated servers to shared plans. Shared plans, which are the most economical and practical for low-traffic websites, can have anywhere from 25 to 150 separated websites hosted from the same web server. When hosting multiple websites on the same server, it is important that one website cannot affect or harm another site. For example, both the web hosting company and its (honest) customers want to prevent one website from, say, reading the connect string information from
Web.config of another website.

ASP.NET allows for web hosting companies to define trust levels, which dictate what operations are permitted by ASP.NET applications. A web hosting company can either use one of the preset trust levels - Full, High, Medium, Low, or Minimal - or can create a custom trust level. Full turst, which is the default, allows ASP.NET applications to execute native code, to read from the Registry and Windows Event Log, and to read and write to files outside of the application's virtual directory. In short, with full trust one web application could delete the entire contents of another web application!

Fortunately, most web hosting companies run in medium trust, which greatly reduces the potential for harm by limiting the set of operations an ASP.NET application can perform. While the protection granted by medium trust is reassuring, its limited functionality can be aggrevating for honest developers. In this article we'll look at how the trust-level is specified, what functionality is limited by medium trust, and some techniques to work around these limitations. Read on to learn more!

Specifying Trust Levels
An ASP.NET application's trust level is specified in
Web.config via the <trust> element:

<trust level="[Full|High|Medium|Low|Minimal]" />

The default trust level is Full, which grants unrestricted permissions. This is a dangerous trust level when working in a shared environment because it allows one web application to interact with the file system of anothers. For example, if you are in a shared environment that physically arranges its shared web applications in a common folder (i.e., C:/Inetpub/wwwroot/WebApplicationName1, C:/Inetpub/wwwroot/WebApplicationName2, ..., C:/Inetpub/wwwroot/WebApplicationNameN, and so on), one web application could use the following code to display the Web.config contents of all of the other web applications on the server:

'Look for Web.config files in parent directories
Dim myPath As String = Request.PhysicalApplicationPath
Dim parentPath As String = String.Concat(myPath, "../")
Dim parentPathInfo As New DirectoryInfo(parentPath)

For Each folder As DirectoryInfo In parentPathInfo.GetDirectories()

    Dim fileOfInterest As String = Path.Combine(folder.FullName, "Web.config")

    If File.Exists(fileOfInterest) Then
      Dim webConfigReader As StreamReader = File.OpenText(fileOfInterest)
      Response.Write(String.Format("<p><b>Data for File {0}:</b></p><p>{1}</p><hr />", fileOfInterest, _                                                 Server.HtmlEncode(webConfigReader.ReadToEnd())))
      webConfigReader.Close()
    End If

Next

Since connection strings are usually placed in Web.config, the nefarious user running the above code would now be able to connect to other customers' databases, where there might be sensitive customer information. The point is, if an ASP.NET application is running in full trust, there's nothing to stop them from reading, creating, modifying, or deleting files in your web application's file system.

Fortunately, most web hosting companies follow the advice in Microsoft's ASP.NET 2.0 Hosting Deployment Guide and place their shared web applications in medium trust. This is accomplished by modifying the machine-level Web.config file in the %windir%/Microsoft.NET/Framework/{version}/CONFIG folder. Moreover, this setting can be locked by the web hosting company. See How To: Use Medium Trust in ASP.NET 2.0 for more information on setting the default trust level for a web server and how to lock this setting. The good news is that if the setting is correctly locked in the machine-level Web.config file, a web application hosted on the server cannot override the setting.

If you attempt to run the above code in a medium trust enviornment, a SecurityException will be thrown when attempting to create a DirectoryInfo object on the parent path.

Medium Trust Permissions
If an application is placed in medium tust, it is limited in the operations it can perform. The How To: Use Medium Trust in ASP.NET 2.0 article summarizes the main limitations as follows:

  • Limited FileIOPermissions: Only files within the application's virtual directory hierarchy can be accessed or modified.
  • Limited OleDbPermissions: the ADO.NET managed OLE DB data provider cannot be used to access databases.
  • Limited EventLogPermissions: you cannot access the Windows Event Log.
  • Limited WebPermission: you cannot make HTTP requests outside of your domain.
  • Limited RegistryPermission: you cannot access the Windows Registry.
  • Limited ReflectionPermission: you cannot use reflection.

Rick Strahl provides a more in-depth look at the limitations imposed by running in medium trust in his blog entry Running ASP.NET in Medium Trust.

Of course, a web hosting company may not necessarily be running strictly within medium trust. They may customize the permissions to, say, allow OleDbPermissions so that their customers can work with the managed OLE DB provider. For a detailed understanding of what permissions are allowed and which ones are denied, contact your web hosting company.

Working Around Medium Trust Limitations
If you are writing an application that may be used by others in a hosted environment, it is important to understand the impact of medium trust and to strive to ensure that your application will work in medium trust. It is important to test your application in a medium trust environment, which you can do by setting the
<trust> element in Web.config. If you are using a third-party component or application that requires certain permissions that are typically denied when running in medium trust, your best bet it to contact your web hosting company and ask them to customize your trust level so that your website can function properly.

Some code that is prohibited from running in medium trust can be replaced by similar code that is runnable under medium trust. One such example is working with configuration information. Under medium trust you cannot use .NET's configuration API to read elements within the <system.web> element in Web.config. This is because the configuration API is not only inspecting your application's Web.config file, but also is examining configuration information up the chain and therefore in areas that fall outside of your web application's virtual directory. However, if you are only interested in the value(s) within the Web.config file in your application, you can read the file using .NET's XML-related classes.

A concrete example of this can be seen in my skmValidator controls. Back in September 2006 I published an article titled Creating Validator Controls for the CheckBox and CheckBoxList, which looked at building a custom validation control for the CheckBox and CheckBoxList Web controls. For reasons that aren't pertinent to this article, this control needed to determine whether the application was configured to emit legacy HTML. By default, ASP.NET 2.0 applications emit XHTML, but they can be configured to emit legacy HTML instead. This information can be set in the <xhtmlConformance> element in Web.config.

In any event, I wrote the code so that it used .NET 2.0's configuration API:

Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
XhtmlConformanceSection xhtmlSection = (XhtmlConformanceSection) cfg.GetSection("system.web/xhtmlConformance");

return xhtmlSection.Mode == XhtmlConformanceMode.Legacy;

This code worked fine when running in full trust (which is how I tested it), but failed in medium trust. Since I failed to test in medium trust, I didn't catch this problem. I therefore wasn't aware of this problem until helpful reader Michael T. pointed it out to me (along with a fix). The fix was to use .NET's XML-related classes to open and read the contents of Web.config, searching for the <xhtmlConformance> element. Michael's code follows:

bool result;

try
{
   string webConfigFile = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "web.config");
   XmlTextReader webConfigReader = new XmlTextReader(new StreamReader(webConfigFile));
   result = ((webConfigReader.ReadToFollowing("xhtmlConformance")) && (webConfigReader.GetAttribute("mode") == "Legacy"));
   webConfigReader.Close();
}
catch
{
   result = false;
}

return result;

Conclusion
Web hosting companies that offer shared plans typically force web applications to run in medium trust so as to prevent one customer from purposefully or accidentally harming another customer's website. Medium trust disables access to the Registry, and the Windows Event Log. It limits code from making external HTTP requests or modifying the file system outside of the application's virtual directory hierarchy.

While the reduced permission set of medium trust helps protect ASP.NET applications in a shared environment, it can introduce problems when integrating third-party applications that might not have been thoroughly tested to work in medium trust (or who need to perform operations that simply cannot be done in medium trust). You may be able to circumvent some of these limitations via alternate techniques, or you may have to contact your web host company and ask them to customize your trust level so that such operations are possible.

Happy Programming!

·  By Scott Mitchell


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值