Skip to content

Add metadata for IFormFile usage with minimal actions #35175

@martincostello

Description

@martincostello

Background and Motivation

As suggested in #34303 (comment), to support binding parameters of type IFormFile with minimal actions, some metadata to allow the form field name for the file would be needed to support names that can't be expressed with C# syntax within the parameter name.

Proposed API

namespace Microsoft.AspNetCore.Http.Metadata
{
+    public interface IFromFileMetadata
+    {
+        string? Name { get; }
+    }
}

namespace Microsoft.AspNetCore.Mvc
{
+    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
+    public class FromFileAttribute : Attribute, IBindingSourceMetadata, IModelNameProvider, IFromFileMetadata
+    {
+        public FromFileAttribute();
+        public FromFileAttribute(string name);
+
+        public BindingSource BindingSource => BindingSource.FormFile;
+        public string? Name { get; set; }
+    }
}

Usage Examples

app.MapPost("/upload", async ([FromFile("file-name")] IFormFile file) =>
{
    using var stream = System.IO.File.OpenWrite("upload.txt");
    await file.CopyToAsync(stream);
});

Alternative Designs

A more explicit name, but having from and form next to each other looks a bit yuck.

namespace Microsoft.AspNetCore.Http.Metadata
{
+   public interface IFromFormFileMetadata
+   {
+       string? Name { get; }
+   }
}

Putting FromFileAttribute in a different namespace so it's not coupled to MVC.

namespace Microsoft.AspNetCore.Http.Metadata
{
+    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
+    public class FromFileAttribute : Attribute, IFromFileMetadata
+    {
+        public FromFileAttribute();
+        public FromFileAttribute(string name);
+
+        public string? Name { get; set; }
+    }
}

Risks

The other [From...] attributes live in the Microsoft.AspNetCore.Mvc namespace so adding another in the same place would make sense, but adding the concrete implementation for [FromFile(...)] to MVC wouldn't be right without also implementing it within model binding there too as a new feature to supplement the existing IFormFile support. Otherwise users of controllers might try and use it and it then not work as expected.

Metadata

Metadata

Assignees

Labels

✔️ Resolution: FixedThe bug or enhancement requested in this issue has been checked-in!api-approvedAPI was approved in API review, it can be implementedold-area-web-frameworks-do-not-use*DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions