简体   繁体   English

WebRequest.create在.NET 3.5类库中引起SecurityException,但在.net 4.5中不引起

[英]WebRequest.create causing SecurityException in a .NET 3.5 class lib, but not in .net 4.5

The following code breaks in a .NET 3.5 class library project, but not in .net 4. I'm stumped and would appreciate any ideas: 以下代码在.NET 3.5类库项目中中断,但在.net 4中没有中断。我很困惑,不胜感激任何想法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using NUnit.Framework;

namespace test2
{

[TestFixture]
public class TestClass
{
    [Test]
    public void Test()
    {
        var request =
             WebRequest.Create("http://www.google.com");

Specific Exception: 具体例外:

System.Security.SecurityException : Request for the permission of type 'System.Net.WebPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, ref StackCrawlMark stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint)
   at System.Net.HttpRequestCreator.Create(Uri Uri)
   at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
   at System.Net.WebRequest.Create(String requestUriString)
   at test2.LaunchRequestInitializeIdsTestFixture.Test()

The answer, as the exception says, is Code Access Security (CAS). 作为例外,答案是代码访问安全性(CAS)。 I am building my code from a network drive (hosted VM). 我正在从网络驱动器(托管的VM)构建代码。 In .NET 3.5 and below, the network drive has lower privileges. 在.NET 3.5及更低版本中,网络驱动器具有较低的特权。 This restriction was turned off for .NET 3.5 SP1 and above. .NET 3.5 SP1和更高版本已禁用此限制。 The following link put me on the right track: http://blogs.msdn.com/b/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx 以下链接将我带入了正确的轨道: http : //blogs.msdn.com/b/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-被推出,从-A-网络share.aspx

The following, run from caspol in the .NET 2 install dir got my code working: .NET 2安装目录中从caspol运行的以下代码使我的代码正常工作:
caspol.exe -m -pp off -ag 1 -url "file:///Z:/*" FullTrust

I got the above command line from this helpful post: https://julianscorner.com/wiki/programming/caspol_network_share 我从此有用的帖子中获得了上述命令行: https : //julianscorner.com/wiki/programming/caspol_network_share

FYI: to restore to defaults, just run "caspol -restore" 仅供参考:要恢复为默认设置,只需运行“ caspol -restore”

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

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