System.Security.Permissions.FileIOPermission 尝试根据信任级别上传文件时出错

System.Security.Permissions.FileIOPermission Error When Trying to Upload a File Based on Trust Levels

我正在 Visual Studio 2013 年开发一个网络应用程序。在我的应用程序中,用户可以上传图像(本地保存到计算机的文件系统,发布后保存到服务器的文件系统)。我将网站发布到我的主机上。但是上传时出现问题。我联系了支持人员,他们告诉我他们不允许 Full Tust,他们允许应用程序的 Medium 信任级别。我在 web.config:

中添加了以下行以将应用程序的信任级别设置为中等
<trust level="Medium" originUrl=""/>

但是当我上传文件尝试时,我遇到了以下错误:

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

有没有办法给自己 fileiopermission 中等信任级别?我正在寻找解决方案数周但没有派上用场。

这是导致问题的代码。

foreach (var file in uploadImages.PostedFiles)
{
    //this line causes the problem
    string filename = Path.GetFileName(new FileInfo(file.FileName).Name);
    string[] extension = filename.Split('.'); 
    string path = Server.MapPath("~/fortunePictures/" + randomString(16) + "." + extension.Last().ToString());
    file.SaveAs(path); 
    DateTime now = DateTime.Now;
    string date = (now.ToString("u"));
    date = date.Substring(0,date.Length-1);
    System.Drawing.Image img = System.Drawing.Image.FromFile(path);
    insertImage(file, path, date, img, userID, fortuneID);
}

这是堆栈跟踪:

[SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
   System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +34
   System.Security.CodeAccessPermission.Demand() +46
   System.Security.Permissions.FileIOPermission.QuickDemand(FileIOPermissionAccess access, String fullPath, Boolean checkForDuplicates, Boolean needFullPath) +157
   System.IO.FileInfo.Init(String fileName, Boolean checkHost) +42
   System.IO.FileInfo..ctor(String fileName) +46
   Fal_Sitesi.kahve.btnUpload_Click(Object sender, EventArgs e) in c:\Users\Ömer\Documents\Visual Studio 2013\Projects\Fal Sitesi\Fal Sitesi\kahve.aspx.cs:84
   System.EventHandler.Invoke(Object sender, EventArgs e) +0
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9717914
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6720
   System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +245
   System.Web.UI.Page.ProcessRequest() +72
   System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +22
   System.Web.UI.Page.ProcessRequest(HttpContext context) +58
   ASP.kahve_aspx.ProcessRequest(HttpContext context) in App_Web_n3utt0vk.0.cs:0
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +341
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

请帮忙。

编辑:到目前为止我做了什么

我根据这个添加了安全策略配置link 我得到了

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Unable to read the security policy file for trust level 'Medium'.

错误。我尝试创建自定义安全策略文件并更改 $AppDir$ 以外的 FileIOPermission 内容。但它也没有帮助。然后我创建新的 web.config 文件。我复制了 web_mediumtrust.config 的内容。但是也没有解决。最后,我删除了 security policy 标签及其所有内容。我用了

<identity impersonate="true" userName="mywebsite.com\ftpUserID" password="ftpPassword"/>

授权连接服务器。但我无法建立联系。 (我不知道为什么,使用相同的数据我可以建立 ftp 连接。

结果没有解决我的问题,我很想解决它。这是我的 web.config.

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation targetFramework="4.5" debug="true"/>
      <httpRuntime/>
      <pages controlRenderingCompatibilityVersion="4.0"/>
      <customErrors mode="Off" defaultRedirect="index.aspx"/>
      <trust level="Medium" originUrl=""/>
    </system.web>
</configuration>

我用这个配置得到 System.Security.SecurityException

编辑2:我根据这个link在我的配置文件中添加了<location path="myAppName" allowOverride="false">。现在应用程序可以在 localhost 上正确运行。但是发布的网站仍然会抛出错误。这是我的 web.config 文件的最新版本:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <location path="myAppName" allowOverride="false">
    <system.web>
      <compilation targetFramework="4.5" debug="true"/>
      <httpRuntime/>
      <pages controlRenderingCompatibilityVersion="4.0"/>
      <customErrors mode="Off" defaultRedirect="index.aspx"/>
      <trust level="Medium" originUrl=""/>
    </system.web>
  </location>
</configuration>

这是中等信任度的常见问题。

您应该可以在配置中使用身份模拟来解决它:

<system.web>
<identity impersonate="true" userName="HOSTING\myUserName" password="myPassword"/>
</system.web>

这里有更多详细信息: https://forums.asp.net/t/1052417.aspx

获得工作登录的确切过程取决于您的托管解决方案,您没有提供任何细节。

您还可以在 SO 上找到一些资源:例如 Unable to upload a file in medium trust 但这个具体问题涉及另一个问题,该问题似乎已因某种原因被删除。

好吧,我找到了解决方案,而且非常简单:(在我的例子中,我使用了

string filename = Path.GetFileName(new FileInfo(file.FileName).Name);

获取文件名,没有必要。我不知道我为什么这么做但是

string filename = file.FileName

足以获取上传文件的文件名。其余代码相同,web.config 文件的最后状态为:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration> 
    <system.web>
      <compilation targetFramework="4.5" debug="true"/>
      <httpRuntime/>
      <pages controlRenderingCompatibilityVersion="4.0"/>
      <customErrors mode="Off" defaultRedirect="index.aspx"/>
      <trust level="Medium" originUrl=""/>
    </system.web>
</configuration>