Skip to content

Commit

Permalink
Reduce memory allocation in AllowedExtensionsAttribute and ContentTyp…
Browse files Browse the repository at this point in the history
…eAttribute (#204)
  • Loading branch information
marcominerva authored Sep 16, 2024
2 parents 891fcdb + 9dbdfe1 commit b853997
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
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

0 comments on commit b853997

Please sign in to comment.