This repository has been archived by the owner on Jul 12, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ff9fb07
commit 7c114ad
Showing
2 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
using FluentValidation; | ||
|
||
namespace RookieShop.ApiService.Filters; | ||
|
||
public sealed class FileValidationFilter : IEndpointFilter | ||
{ | ||
private const int MaxFileSize = 1048576; | ||
|
||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) | ||
{ | ||
var request = context.HttpContext.Request; | ||
var formCollection = await request.ReadFormAsync(); | ||
var files = formCollection.Files; | ||
|
||
if (files.Count == 0) | ||
return await next(context); | ||
|
||
foreach (var file in files) | ||
{ | ||
switch (file.Length) | ||
{ | ||
case 0: | ||
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; | ||
throw new ValidationException("File is empty."); | ||
case > MaxFileSize: | ||
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; | ||
throw new ValidationException($"File size is too large. Max file size is {MaxFileSize / 1024} KB."); | ||
} | ||
|
||
List<string> allowedExtensions = [".jpg", ".jpeg", ".png"]; | ||
var extension = Path.GetExtension(file.FileName); | ||
|
||
if (allowedExtensions.Contains(extension)) continue; | ||
|
||
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; | ||
throw new ValidationException($"File extension {extension} is not allowed."); | ||
} | ||
|
||
return await next(context); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters