一键创建netcore8.0项目
配置模版略
直接上代码:
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.IO.Compression;namespace SaaS.OfficialWebSite.Web.Controllers
{public class ProjectGenController : Controller{public IActionResult Index(){return View();}[HttpPost]public async Task<IActionResult> GenerateProject([FromBody] ProjectRequest request){if (string.IsNullOrWhiteSpace(request.ProjectName) ||!System.Text.RegularExpressions.Regex.IsMatch(request.ProjectName, @"^[A-Za-z0-9_\-]+$")){return BadRequest("项目名称只能包含字母、数字、下划线和连字符");}try{// 创建临时目录var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());Directory.CreateDirectory(tempDir);// 执行 dotnet new 命令var processStartInfo = new ProcessStartInfo{FileName = "dotnet",Arguments = $"new unt-template -n {request.ProjectName} -o {tempDir}",RedirectStandardOutput = true,RedirectStandardError = true,UseShellExecute = false,CreateNoWindow = true,// 添加环境变量Environment ={["USERPROFILE"] = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),["HOME"] = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}};using (var process = Process.Start(processStartInfo)){await process.WaitForExitAsync();if (process.ExitCode != 0){var error = await process.StandardError.ReadToEndAsync();return BadRequest($"项目生成失败: {error}");}}// 创建内存流用于zip文件var memoryStream = new MemoryStream();using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)){// 递归添加所有文件到zipawait AddDirectoryToZip(zipArchive, tempDir, "");}// 清理临时目录Directory.Delete(tempDir, true);// 返回zip文件memoryStream.Position = 0;return File(memoryStream, "application/zip", $"{request.ProjectName}.zip");}catch (Exception ex){return StatusCode(500, $"服务器错误: {ex.Message}");}}private async Task AddDirectoryToZip(ZipArchive zipArchive, string sourceDir, string entryPrefix){foreach (var file in Directory.GetFiles(sourceDir)){var entryName = Path.Combine(entryPrefix, Path.GetFileName(file));var entry = zipArchive.CreateEntry(entryName);using (var entryStream = entry.Open())using (var fileStream = System.IO.File.OpenRead(file)){await fileStream.CopyToAsync(entryStream);}}foreach (var dir in Directory.GetDirectories(sourceDir)){var dirName = Path.GetFileName(dir);var newEntryPrefix = Path.Combine(entryPrefix, dirName);await AddDirectoryToZip(zipArchive, dir, newEntryPrefix);}}}public class ProjectRequest{public string ProjectName { get; set; }}
}
运行效果:Necore项目生成器