Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce memory allocation in AllowedExtensionsAttribute and ContentTypeAttribute #204

Merged
merged 7 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ namespace TinyHelpers.AspNetCore.DataAnnotations;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class AllowedExtensionsAttribute(params string[] extensions) : ValidationAttribute("Only files with the following extensions are supported: {0}")
{
private readonly IEnumerable<string> extensions = extensions.Select(e => e.ToLowerInvariant().Replace("*.", string.Empty));
private readonly IEnumerable<string> extensions = extensions.Select(e => e.Replace("*.", string.Empty));

protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is IFormFile file)
{
var extension = Path.GetExtension(file.FileName).ToLower()[1..];
if (!extensions.Contains(extension))
var extension = Path.GetExtension(file.FileName)[1..];
if (!extensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class ContentTypeAttribute : ValidationAttribute
public ContentTypeAttribute(params string[] validContentTypes)
: base(DefaultErrorMessage)
{
this.validContentTypes = validContentTypes.Select(s => s.ToLowerInvariant());
this.validContentTypes = validContentTypes;
}

public ContentTypeAttribute(FileType fileType)
Expand All @@ -43,7 +43,7 @@ public ContentTypeAttribute(FileType fileType)

protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is IFormFile formFile && !validContentTypes.Contains(formFile.ContentType))
if (value is IFormFile formFile && !validContentTypes.Contains(formFile.ContentType, StringComparer.OrdinalIgnoreCase))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
Expand Down
Loading