LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

【C#】自动检测Windows Server服务器是否已经安装并配置IIS管理器的ASP和ASP.NET(.aspx)支持代码

admin
2025年6月11日 9:19 本文热度 125

以下是完整的C#代码,用于Windows Server服务器自动安装并配置IIS的ASP(经典ASP)和ASP.NET(.aspx)支持。代码包含功能检测,只有在未安装时才执行安装操作:

using System;

using System.Diagnostics;

using Microsoft.Web.Administration;


class IISFullSupportInstaller

{

    static void Main()

    {

        try

        {

            Console.WriteLine("正在检测IIS功能安装状态...");

            

            bool needRestart = false;

            

            // 安装缺失的功能

            if (!IsASPInstalled())

            {

                Console.WriteLine("检测到经典ASP功能未安装");

                InstallIISFeature("IIS-ASP");

                needRestart = true;

            }

            

            if (!IsASPNETInstalled())

            {

                Console.WriteLine("检测到ASP.NET功能未安装");

                InstallIISFeature("IIS-ASPNET45");

                needRestart = true;

            }

            

            // 配置IIS

            if (needRestart)

            {

                Console.WriteLine("需要重启后继续配置,按任意键重启计算机...");

                Console.ReadKey();

                RestartComputer();

            }

            else

            {

                ConfigureIIS();

                Console.WriteLine("ASP和ASP.NET支持已成功配置!");

            }

        }

        catch (Exception ex)

        {

            Console.WriteLine($"操作失败: {ex.Message}");

            Console.WriteLine("请以管理员身份运行此程序");

        }

    }


    // 检查经典ASP是否已安装

    static bool IsASPInstalled()

    {

        using (ServerManager serverManager = new ServerManager())

        {

            try

            {

                // 尝试获取ASP配置部分,如果抛出异常说明未安装

                var aspSection = serverManager.GetApplicationHostConfiguration().GetSection("system.webServer/asp");

                return true;

            }

            catch

            {

                return false;

            }

        }

    }


    // 检查ASP.NET是否已安装

    static bool IsASPNETInstalled()

    {

        using (ServerManager serverManager = new ServerManager())

        {

            try

            {

                // 检查.NET Framework处理程序是否存在

                var config = serverManager.GetApplicationHostConfiguration();

                var runtimeSection = config.GetSection("system.webServer/runtime");

                return true;

            }

            catch

            {

                return false;

            }

        }

    }


    // 安装IIS功能

    static void InstallIISFeature(string featureName)

    {

        ProcessStartInfo startInfo = new ProcessStartInfo

        {

            FileName = "dism.exe",

            Arguments = $"/Online /Enable-Feature /FeatureName:{featureName} /All /NoRestart",

            RedirectStandardOutput = true,

            RedirectStandardError = true,

            UseShellExecute = false,

            CreateNoWindow = true

        };


        using (Process process = new Process { StartInfo = startInfo })

        {

            Console.WriteLine($"正在安装 {featureName} ...");

            process.Start();

            string output = process.StandardOutput.ReadToEnd();

            string error = process.StandardError.ReadToEnd();

            process.WaitForExit();


            if (process.ExitCode != 0)

            {

                throw new Exception($"{featureName} 安装失败 (代码 {process.ExitCode}): {error}");

            }

            

            if (!output.Contains("操作成功完成"))

            {

                throw new Exception($"{featureName} 安装未完成: " + output);

            }

            

            Console.WriteLine($"{featureName} 安装成功");

        }

    }


    // 配置IIS支持ASP和ASP.NET

    static void ConfigureIIS()

    {

        using (ServerManager serverManager = new ServerManager())

        {

            Console.WriteLine("正在配置IIS支持...");

            

            // 1. 配置经典ASP支持

            if (!IsASPConfigured(serverManager))

            {

                Console.WriteLine("配置经典ASP支持");

                ConfigureClassicASP(serverManager);

            }

            

            // 2. 配置ASP.NET支持

            if (!IsASPNETConfigured(serverManager))

            {

                Console.WriteLine("配置ASP.NET支持");

                ConfigureASPNET(serverManager);

            }

            

            // 3. 保存所有更改

            serverManager.CommitChanges();

            Console.WriteLine("配置保存成功");

        }

    }


    // 检查经典ASP是否已配置

    static bool IsASPConfigured(ServerManager serverManager)

    {

        try

        {

            var config = serverManager.GetApplicationHostConfiguration();

            var restrictions = config.GetSection("system.webServer/security/isapiCgiRestriction").GetCollection();

            

            foreach (var item in restrictions)

            {

                if (item["path"].ToString().EndsWith("asp.dll", StringComparison.OrdinalIgnoreCase) && 

                    (bool)item["allowed"])

                {

                    return true;

                }

            }

            return false;

        }

        catch

        {

            return false;

        }

    }


    // 配置经典ASP

    static void ConfigureClassicASP(ServerManager serverManager)

    {

        var config = serverManager.GetApplicationHostConfiguration();

        

        // 启用ASP ISAPI扩展

        var isapiSection = config.GetSection("system.webServer/security/isapiCgiRestriction");

        var restrictions = isapiSection.GetCollection();

        

        ConfigurationElement aspExtension = restrictions.CreateElement();

        aspExtension["path"] = @"%windir%\system32\inetsrv\asp.dll";

        aspExtension["allowed"] = true;

        aspExtension["description"] = "ASP Classic Support";

        restrictions.Add(aspExtension);


        // 配置ASP全局设置

        ConfigurationSection aspSection = config.GetSection("system.webServer/asp");

        aspSection["enableParentPaths"] = true;

        aspSection["bufferingOn"] = true;

        aspSection["scriptErrorSentToBrowser"] = true;


        // 为默认网站添加ASP处理程序映射

        Configuration webConfig = serverManager.GetWebConfiguration("Default Web Site");

        ConfigurationSection handlersSection = webConfig.GetSection("system.webServer/handlers");

        ConfigurationElementCollection handlers = handlersSection.GetCollection();


        ConfigurationElement aspHandler = handlers.CreateElement();

        aspHandler["name"] = "ASPClassic";

        aspHandler["path"] = "*.asp";

        aspHandler["verb"] = "GET,HEAD,POST";

        aspHandler["modules"] = "IsapiModule";

        aspHandler["scriptProcessor"] = @"%windir%\system32\inetsrv\asp.dll";

        aspHandler["resourceType"] = "File";

        handlers.Add(aspHandler);

    }


    // 检查ASP.NET是否已配置

    static bool IsASPNETConfigured(ServerManager serverManager)

    {

        try

        {

            var siteConfig = serverManager.GetWebConfiguration("Default Web Site");

            var handlers = siteConfig.GetSection("system.webServer/handlers").GetCollection();

            

            foreach (var handler in handlers)

            {

                if (handler["path"].ToString() == "*.aspx" && 

                    handler["type"] != null)

                {

                    return true;

                }

            }

            return false;

        }

        catch

        {

            return false;

        }

    }


    // 配置ASP.NET支持

    static void ConfigureASPNET(ServerManager serverManager)

    {

        // 设置应用程序池使用.NET 4.x

        bool poolExists = false;

        foreach (var pool in serverManager.ApplicationPools)

        {

            if (pool.Name == "DefaultAppPool")

            {

                pool.ManagedRuntimeVersion = "v4.0";

                pool.ManagedPipelineMode = ManagedPipelineMode.Integrated;

                pool.AutoStart = true;

                pool.Enable32BitAppOnWin64 = true; // 根据需求设置

                poolExists = true;

                break;

            }

        }


        if (!poolExists)

        {

            ApplicationPool newPool = serverManager.ApplicationPools.Add("DefaultAppPool");

            newPool.ManagedRuntimeVersion = "v4.0";

            newPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;

        }


        // 确保默认网站使用正确的应用程序池

        Site defaultSite = serverManager.Sites["Default Web Site"];

        if (defaultSite != null)

        {

            defaultSite.ApplicationDefaults.ApplicationPoolName = "DefaultAppPool";

            

            // 添加ASP.NET处理程序映射

            Configuration siteConfig = serverManager.GetWebConfiguration("Default Web Site");

            ConfigurationSection handlersSection = siteConfig.GetSection("system.webServer/handlers");

            ConfigurationElementCollection handlers = handlersSection.GetCollection();

            

            // 检查是否已存在

            bool handlerExists = false;

            foreach (var handler in handlers)

            {

                if (handler["path"].ToString() == "*.aspx")

                {

                    handlerExists = true;

                    break;

                }

            }

            

            if (!handlerExists)

            {

                ConfigurationElement aspxHandler = handlers.CreateElement();

                aspxHandler["name"] = "ASP.NET";

                aspxHandler["path"] = "*.aspx";

                aspxHandler["verb"] = "*";

                aspxHandler["type"] = "System.Web.UI.PageHandlerFactory";

                aspxHandler["resourceType"] = "Unspecified";

                aspxHandler["requireAccess"] = "Script";

                handlers.Add(aspxHandler);

            }

        }

    }


    // 重启计算机

    static void RestartComputer()

    {

        ProcessStartInfo startInfo = new ProcessStartInfo

        {

            FileName = "shutdown.exe",

            Arguments = "/r /t 0",

            Verb = "runas", // 管理员权限

            UseShellExecute = true

        };


        try

        {

            Process.Start(startInfo);

            Environment.Exit(0);

        }

        catch (Exception ex)

        {

            throw new Exception($"重启失败: {ex.Message}\n请手动重启计算机以完成安装");

        }

    }

}

代码功能说明:

1、智能检测机制

  • IsASPInstalled():检查经典ASP功能是否安装

  • IsASPNETInstalled():检查ASP.NET功能是否安装

  • IsASPConfigured():检查ASP是否配置正确

  • IsASPNETConfigured():检查ASP.NET是否配置正确

2、安装功能

  • 使用DISM安装缺失的IIS功能:

  • IIS-ASP:经典ASP支持

  • IIS-ASPNET45:ASP.NET 4.x支持

  • 自动处理安装结果和错误

​3、配置IIS

 经典ASP配置

  • 启用asp.dll ISAPI扩展

  • 配置父路径、缓冲和错误显示

  • 添加*.asp处理程序映射

 ASP.NET配置

  • 设置应用程序池使用.NET 4.0

  • 配置集成管道模式

  • 添加*.aspx处理程序映射

  • 确保默认网站使用正确的应用池

4、重启管理

  • 需要重启时提示用户

  • 自动以管理员权限执行重启

使用说明:

1、项目配置(.csproj文件):

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0-windows</TargetFramework> <Platforms>x64</Platforms> <RuntimeIdentifier>win10-x64</RuntimeIdentifier> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Web.Administration" Version="11.1.0" /> </ItemGroup></Project>

2、运行要求

  • 必须以管理员身份运行

  • Windows 7/Server 2008 R2或更高版本

  • 需要互联网连接以下载IIS组件(如果需要)

3、验证方法

  • 创建测试文件 C:\inetpub\wwwroot\test.asp

<%@ Language=VBScript %>

<% Response.Write("ASP Works! Time: " & Now()) %>

  • 创建测试文件 C:\inetpub\wwwroot\test.aspx

<%@ Page Language="C#" %>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)

    {

        lblMessage.Text = "ASP.NET Works! Time: " + DateTime.Now;

    }

</script>

<html>

<body>

    <asp:Label ID="lblMessage" runat="server" />

</body>

</html>

  • 访问以下URL验证:

  http://localhost/test.asp

  http://localhost/test.aspx

处理流程:

注意事项:

1、重启要求

  • 安装IIS组件后需要重启才能继续配置

  • 代码会自动提示重启,重启后需再次运行程序完成配置

2、自定义站点

  • 默认配置"Default Web Site"

  • 如需自定义站点,修改代码中的站点名称

3、32位支持

  • 默认启用32位应用支持(Enable32BitAppOnWin64 = true

  • 对于纯64位环境,可设置为false

4、错误处理

  • 代码包含详细错误处理

  • 安装失败时会显示具体原因

  • 权限不足时会提示使用管理员身份运行

此代码提供了完整的端到端解决方案,从检测、安装到配置,全面支持ASP和ASP.NET页面,确保您的网站能同时处理.asp和.aspx文件。


该文章在 2025/6/11 9:21:47 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved