0

I am attempting to use minimal api to develop an image uploader. I have the program.cs file code debugged and it launches to a webpage with an http 404 error. This is the entirety of the code.

using System.Text.Json;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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();

I have found that when i remove

c =>
    {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
    c.RoutePrefix = string.Empty;
    }

from

// 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;
    });
}

Then it goes straight to the swagger UI, BUT there is nothing on the page other than the basic ui telling me that there are no operations defined in the spec

Helen
  • 87,344
  • 17
  • 243
  • 314
  • If not clear, I am asking how would I go about displaying what i need to display? A button to upload image, a submit button, etc. I did have an html page but it was not working either. – Curtis Antisdel Jul 01 '23 at 06:33
  • I am beginning to realize i need to add an html form back. How should that look to make sure it appears with minimal api in .net 6? – Curtis Antisdel Jul 01 '23 at 06:44

0 Answers0