dotnet / dotnet/aspnetcore

How can I use multiple attribute for one parameter of model binding

Open
#47,530 9 comments 0 reactions 0 assignees View on GitHub
area-mvc Docs net8_docathon
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

- [X] I have searched the existing issues

I want to handle *the same parameter* from both the query string and the header in the same action but it ignores all but the first attribute.

```cs
public async Task Index([FromQuery,FromHeader] string foo = default) {
//
}
```

Not entirely sure, but you should allow multiple usages for attributes of model binding. `AllowMultiple = true`
```cs
namespace Microsoft.AspNetCore.Mvc {
///
/// Specifies that a parameter or property should be bound using the request headers.
///
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class FromHeaderAttribute : Attribute, IBindingSourceMetadata, IModelNameProvider, IFromHeaderMetadata {
///
public BindingSource BindingSource => BindingSource.Header;

///
public string? Name { get; set; }
}
}
```

Or you should append a new attribute that can be passed as a `List` collection parameter to the framework.
```cs

public interface IBindingSourcesMetadata {
List BindingSources { get; }
}

public class FromBindingSourceAttribute : Attribute, IBindingSourcesMetadata, IModelNameProvider {
public FromBindingSourceAttribute (List bindingSources) {
BindingSources = bindingSources;
}

public List BindingSources { get; }

public string? Name { get; set; }
}
```

An exception should be thrown if two sources are passed at the same time by developer.

![image](https://user-images.githubusercontent.com/55924924/229340281-5f249264-f93c-4cad-a32f-f2d8bfb07e76.png)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.