【问题标题】:WebRequest.create causing SecurityException in a .NET 3.5 class lib, but not in .net 4.5WebRequest.create 在 .NET 3.5 类库中导致 SecurityException,但在 .net 4.5 中没有
【发布时间】:2014-05-28 04:36:42
【问题描述】:

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

【问题讨论】:

    标签: c# .net


    【解决方案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”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-25
      • 2016-03-25
      • 2011-04-04
      • 2012-09-05
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多