diff --git a/fundamentals/minimal-apis/samples/IFormFile/IFormFile.csproj b/fundamentals/minimal-apis/samples/IFormFile/IFormFile.csproj new file mode 100644 index 0000000..1b28a01 --- /dev/null +++ b/fundamentals/minimal-apis/samples/IFormFile/IFormFile.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/fundamentals/minimal-apis/samples/IFormFile/Program.cs b/fundamentals/minimal-apis/samples/IFormFile/Program.cs new file mode 100644 index 0000000..3d856dd --- /dev/null +++ b/fundamentals/minimal-apis/samples/IFormFile/Program.cs @@ -0,0 +1,71 @@ +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; + +var builder = WebApplication.CreateBuilder(); + +builder.Services.AddAntiforgery(); + +var app = builder.Build(); +app.UseAntiforgery(); +string GetOrCreateFilePath(string fileName, string filesDirectory = "uploadFiles") +{ + var directoryPath = Path.Combine(app.Environment.ContentRootPath, filesDirectory); + Directory.CreateDirectory(directoryPath); + return Path.Combine(directoryPath, fileName); +} + +async Task UploadFileWithName(IFormFile file, string fileSaveName) +{ + var filePath = GetOrCreateFilePath(fileSaveName); + await using var fileStream = new FileStream(filePath, FileMode.Create); + await file.CopyToAsync(fileStream); +} + +app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) => +{ + var token = antiforgery.GetAndStoreTokens(context); + var html = $""" + + +
+ +
+ +
+ +
+ + +
+ + + """; + + return Results.Content(html, "text/html"); +}); + +app.MapPost("/upload", async Task, + BadRequest>> ([FromForm] FileUpload file, HttpContext context, IAntiforgery antiforgery) => +{ + try + { + await antiforgery.ValidateRequestAsync(context); + await UploadFileWithName(file.FileDocument, file.Name); + return TypedResults.Ok($"Your file with the description: {file.Description} has been uploaded successfully"); + } + catch (AntiforgeryValidationException e) + { + return TypedResults.BadRequest("Invalid anti-forgery token"); + } +}); + +app.Run(); + +public class FileUpload +{ + public string? Name { get; set; } + public string? Description { get; set; } + public IFormFile? FileDocument { get; set; } +} diff --git a/fundamentals/minimal-apis/samples/IFormFile/Readme.txt b/fundamentals/minimal-apis/samples/IFormFile/Readme.txt deleted file mode 100644 index 84c16fc..0000000 --- a/fundamentals/minimal-apis/samples/IFormFile/Readme.txt +++ /dev/null @@ -1 +0,0 @@ -Delete after adding sample \ No newline at end of file