WebRequest.create在.NET 3.5类lib中导致SecurityException,但在.net 4.5中没有

时间:2014-05-28 04:36:43

标签: c# .net

以下代码在.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");

特殊例外:

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()

1 个答案:

答案 0 :(得分:1)

除了例外,答案是代码访问安全性(CAS)。我正在从网络驱动器(托管的VM)构建我的代码。在.NET 3.5及更低版本中,网络驱动器具有较低的权限。对.NET 3.5 SP1及更高版本禁用此限制。以下链接让我走上正轨: 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

以下,从 .NET 2安装目录中的caspol运行,使我的代码正常工作:
caspol.exe -m -pp off -ag 1 -url "file:///Z:/*" FullTrust

我从这篇有用的帖子中得到了上面的命令行: https://julianscorner.com/wiki/programming/caspol_network_share

供参考: 恢复默认值,只需运行“caspol -restore”