Minimal API图片上传器Swagger UI异常:启动404且无API操作显示
问题:Minimal API图片上传器的404错误与Swagger显示异常
我用Minimal API开发图片上传器,调试Program.cs代码后启动网页出现HTTP 404错误。完整代码如下:
using System.Text.Json; using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); builder.Services.AddRazorPages(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1"); c.RoutePrefix = string.Empty; }); } app.UseHttpsRedirection(); app.MapPost("/submit-form", async (HttpContext context) => { var form = await context.Request.ReadFormAsync(); var title = form["imageTitle"]; var file = form.Files["imageFile"]; // Perform validation checks if (string.IsNullOrEmpty(title)) { context.Response.StatusCode = 400; // Bad Request await context.Response.WriteAsync("Image title is required."); return; } if (file == null || file.Length == 0) { context.Response.StatusCode = 400; // Bad Request await context.Response.WriteAsync("No image file uploaded."); return; } var allowedExtensions = new[] { ".jpeg", ".jpg", ".png", ".gif" }; var fileExtension = Path.GetExtension(file.FileName); if (!allowedExtensions.Contains(fileExtension.ToLower())) { context.Response.StatusCode = 400; // Bad Request await context.Response.WriteAsync("Invalid file format. Accepted formats: JPEG, PNG, GIF."); return; } // If validation passes, continue with further actions // Generate unique ID for the image var imageId = Guid.NewGuid().ToString(); // Store image information var imageInfo = new { ImageId = imageId, Title = title, file.FileName }; // Serialize image information to JSON var json = JsonSerializer.Serialize(imageInfo); // Store JSON data in a file on disk var filePath = Path.Combine(Directory.GetCurrentDirectory(), "images", $"{imageId}.json"); await File.WriteAllTextAsync(filePath, json); // Redirect to the page with the unique ID var redirectUrl = $"/picture/{imageId}"; context.Response.Redirect(redirectUrl); }); app.MapGet("/picture/{id}", async (HttpContext context) => { var imageId = context.Request.RouteValues["id"] as string; var filePath = Path.Combine(Directory.GetCurrentDirectory(), "images", $"{imageId}.json"); if (!File.Exists(filePath)) { context.Response.StatusCode = 404; // Not Found await context.Response.WriteAsync("Image not found."); return; } // Read the JSON data from the file var json = await File.ReadAllTextAsync(filePath); // Deserialize the JSON data to retrieve the image information var imageInfo = JsonSerializer.Deserialize<Dictionary<string, object>>(json); // Get the title from imageInfo dictionary string title; if (imageInfo != null && imageInfo.TryGetValue("Title", out _)) { title = (string)imageInfo["Title"]; } else { title = string.Empty; } // Get the file name from imageInfo dictionary string fileName; if (imageInfo != null && imageInfo.TryGetValue("FileName", out var fileNameObj) && fileNameObj is string) { fileName = (string)fileNameObj; } else { fileName = string.Empty; } // Render a page that displays the image title and the image itself await context.Response.WriteAsync($"<h1>{title}</h1>"); if (imageInfo != null) { await context.Response.WriteAsync($"<img src=\"/images/{imageInfo[\"FileName\"]}\" alt=\"{title}\">"); } else { await context.Response.WriteAsync("Image information is not available."); } }); app.Run();
我尝试移除SwaggerUI的配置委托:
c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1"); c.RoutePrefix = string.Empty; }
即将原来的管道配置代码修改为:
// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }
修改后能直接进入Swagger UI,但页面仅显示基础界面,提示**“规范中未定义任何操作”**。
内容的提问来源于stack exchange,提问作者Curtis Antisdel
相关产品推荐
相关产品推荐

