如何使用应用程序池标识而不是记录的用户标识上传文件 - ASP.NET MVC 模拟

How to Upload File using Application Pool identity instead of Logged User Identity- ASP.NET MVC Impersonation

我正在开发 ASP.NET MVC Web 应用程序。我有这样的情况,我想使用应用程序池身份而不是记录的用户身份上传文件。我只想在上传文件时使用应用程序池标识。所有其他地方,我想使用登录的用户身份本身。 应用程序托管在两台服务器上,Server1 和 Server2.Shared 文件夹位于 Server1.

目前我正在上传文件如下图

    [HttpPost]
    public JsonResult Upload()
    {
         string fileUniqueName = string.Empty;

        try
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                string fileName = file.FileName;
                fileUniqueName = string.Format("{0}_{1}_{2}",
                Path.GetFileNameWithoutExtension(file.FileName),
                DateTime.Now.ToString("yyyyMMdd_HHmmss_FFF"),
                Path.GetExtension(file.FileName));
                string tempFileUploadFolderPath = ConfigurationManager.AppSettings["TempFolderPath"];
                Directory.CreateDirectory(tempFileUploadFolderPath);
                string fileFullpath = Path.Combine(tempFileUploadFolderPath, fileUniqueName);
                file.SaveAs(fileFullpath);
            }
        }
        catch(Exception)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return new JsonResult
            {
                Data = ""
            };
        }
        
        return new JsonResult
        {
            Data = fileUniqueName
        };
    }

我在 web.config

中有以下设置
<authentication mode="Windows" />
<identity impersonate="true" />

任何人都可以帮助重写上面的代码,其中文件上传在应用程序池标识而不是记录的用户标识上工作。文件正在上传到托管应用程序的文件夹。

看完文档和实际测试后,我现在可以给你一个详细的答案。

如您在上一帖中所述,如果非AD组的用户希望能够将文件上传到该文件夹​​,则需要以应用程序池身份执行上传操作。但是您启用了模拟,因此当您以非 AD 组用户身份登录时,IIS 将使用您的登录帐户覆盖应用程序池标识。 如果将模拟设置为 false,上传将以应用程序池身份执行,文件将保存到文件夹中。

但是如果在整个站点中将impersonate设置为false,则非AD用户在其他页面上进行的任何操作也将以应用程序池身份进行。

所以可以将整个站点的impersonate设置为true,只有上传页面impersonate为false。只需select IIS 中的视图文件夹,切换到内容视图,select cshtml 并右键单击切换到特征,然后在身份验证中禁用模拟。像这样

一些有用的博客可以参考:Users access to disk

When using Windows authentication, the application pool identity (e.g. IIS Apppool\Site001) is used for some access but the Windows account (e.g. User1) is used for other access. It depends on the impersonation settings of your application or framework that you’re using. Therefore, you would generally need to grant access to the application pool identity, plus every Windows account (e.g. User1, User2, User99) which needs access to your site.

Identiies in IIS

您应该能够使用 web.config 中的 <location> 元素控制每个路径的身份验证设置。

像这样:

<location path="/upload">
  <system.web>
     <authentication mode="Windows"/>
     <identity impersonate="false"/>
  </system.web>
</location>