.Net Core 生成管理员权限的应用程序

发布于:2024-09-19 ⋅ 阅读:(17) ⋅ 点赞:(0)
  • 创建一个ASP.NET Core Web API项目

  • 给解决方案设置一个名称

  • 选择一个目标框架,这里选择的是 .NET 8.0框架

  • 在Porperties文件夹中添加一个app.manifest文件

  • 设置app.manifest文件属性,生成操作设置为嵌入的资源

双击解决方案名称,编辑WebApplication22.csproj文件,在.csproj文件中加入一行代码

<ApplicationManifest>Properties\app.manifest</ApplicationManifest>

.csproj配置文件如下 

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
	<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
  </PropertyGroup>
  <ItemGroup>
    <EmbeddedResource Include="Properties\app.manifest" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
  </ItemGroup>
</Project>

app.manifest文件配置如下

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
	<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
	<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
		<security>
			<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
			<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
			</requestedPrivileges>
			<applicationRequestMinimum>
				<defaultAssemblyRequest permissionSetReference="Custom" />
				<PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" />
			</applicationRequestMinimum>
		</security>
	</trustInfo>
	<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
		<application>
		</application>
	</compatibility>
</assembly>

需要注意的是,需要把requestedExecutionLevel节点中的level值设置为“requireAdministrator”

  • 此时重新生成解决方案发现我们的exe程序就会有一个盾牌的标识,说明是成功设置为了管理员身份启动。

  • 另外我们可以在Program.cs文件中的Main方法中加入如下代码,用于判断程序是否以管理员身份运行:
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator)) //必须是管理员身份运行
{
    //CreateHostBuilder(args).Build().Run();
}

附:

参考网址【搞懂.NET应用程序管理员权限:三种简单方法一网打尽_net 权限管理-CSDN博客


网站公告

今日签到

点亮在社区的每一天
去签到