首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 給站點目錄新增 ASPNET 使用者權限

     編輯:關於ASP.NET

程式碼動態設定資料夾 ACL:授予 ASPNET 完整控制權限

完整代碼

using System;
using System.IO;
using System.Net;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Web.UI;

public partial class ACLChange : Page
{
    private string strDir = "images";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) AddDirectorySecurity();
    }

    private void AddDirectorySecurity()
    {
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(strDir));

        // 移除唯讀屬性
        if ((dirInfo.Attributes & FileAttributes.ReadOnly) != 0)
            dirInfo.Attributes = FileAttributes.Normal;

        DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
        string domain = Dns.GetHostName(); // 本機網域/電腦名

        dirSecurity.AddAccessRule(new FileSystemAccessRule(
            domain + @"\ASPNET",
            FileSystemRights.FullControl,
            AccessControlType.Allow));

        dirInfo.SetAccessControl(dirSecurity);
    }
}

關鍵步驟解析

  1. Server.MapPath 取得實體路徑。
  2. 清除 ReadOnly 屬性,否則 ACL 修改可能失效。
  3. GetAccessControl 取得現有 ACL。
  4. 建立 FileSystemAccessRule:身分 機器名\ASPNET、權限 FullControl、類型 Allow。
  5. SetAccessControl 寫回檔案系統。

適用場景

  • 部署腳本自動化設定上傳目錄權限。
  • 共享主機環境無法手動設定 IIS 權限時。
    注意: IIS 7+ 應用程式池身分預設為 IIS_IUSRS 或 ApplicationPoolIdentity,非 ASPNET,需依實際身分調整。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved