dotnet / dotnet/aspnetcore

Add .ctor(string) to FromHeaderAttribute and FromQueryAttribute

Open
#36,418 4 comments 1 reaction 0 assignees View on GitHub
api-suggestion area-minimal feature-minimal-actions triage-focus
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

## Background and Motivation

When using Minimal APIs, using explicit query string or header parameter names using attributes requires a less-minimal amount of attribute declaration that would be possible if the relevant attributes did not only have a default constructor.

## Proposed API

```diff
namespace Microsoft.AspNetCore.Mvc
{
public static class FromHeaderAttribute
{
+ public FromHeaderAttribute(string name)
}

public static class FromQueryAttribute
{
+ public FromQueryAttribute(string name)
}

public static class FromRouteAttribute
{
+ public FromRouteAttribute(string name)
}
}
```

## Usage Examples

```csharp
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/search", (
[FromQuery("q")] string? query,
[FromHeader("User-Agent")] string? userAgent) =>
{
return $@"You searched for ""{query}"" using ""{userAgent}"".";
});

app.Run();

```

## Alternative Designs

None, retain the existing usage patterns.

```csharp
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/search", (
[FromQuery(Name = "q")] string? query,
[FromHeader(Name = "User-Agent")] string? userAgent) =>
{
return $@"You searched for ""{query}"" using ""{userAgent}"".";
});

app.Run();
```

## Risks

None that I'm aware of.

EDIT: Added `FromRouteAttribute` too.

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.