Multiple Get Methods with the Action Method Selector Attribute in .NET Core 10
Download full source code.
Here is the previous post I wrote about this. A little has changed since then.
If you update the code to compile with .NET Core 10, the default Get() method will be called for all requests.
Here is the updated QueryStringConstraint class, which inherits from ActionMethodSelectorAttribute.
1public sealed class QueryStringConstraint : ActionMethodSelectorAttribute
2{
3 public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
4 {
5 var queryStringKeys = routeContext.HttpContext.Request.Query.Keys
6 .Select(key => key.ToLowerInvariant())
7 .ToList();
8 var methodParameterNames = action.Parameters
9 .Select(parameter => parameter.Name.ToLowerInvariant())
10 .ToList();
11
12 if (queryStringKeys.Any(key => !methodParameterNames.Contains(key)))
13 {
14 return false;
15 }
16
17 foreach (var parameter in action.Parameters)
18 {
19 var parameterName = parameter.Name.ToLowerInvariant();
20 var isMissing = queryStringKeys.All(key => key != parameterName);
21
22 if (isMissing && Nullable.GetUnderlyingType(parameter.ParameterType) == null)
23 {
24 return false;
25 }
26 }
27
28 return true;
29 }
30}The Get() method also needs to be decorated with the QueryStringConstraint attribute.
1using Microsoft.AspNetCore.Mvc;
2
3namespace ActionDescriptorRoutingCore10.Controllers;
4
5[ApiController]
6[Route("api/[controller]")]
7public class ValuesController : ControllerBase
8{
9 [HttpGet]
10 [QueryStringConstraint]
11 public IEnumerable<string> Get()
12 {
13 return ["value1", "value2"];
14 }
15
16 [HttpGet("{id}")]
17 public int Get(int id)
18 {
19 return id;
20 }
21
22 [HttpGet]
23 [QueryStringConstraint]
24 public string GetAnother(int id, int another)
25 {
26 return $"GetAnother {id} {another}";
27 }
28
29 [HttpGet]
30 [QueryStringConstraint]
31 public string GetSomething(int id, int something)
32 {
33 return $"GetSomething {id} {something}";
34 }
35
36 [HttpGet]
37 [QueryStringConstraint]
38 public string GetWithNullables(int id, int? myNullable)
39 {
40 return $"GetWithNullables {id} {myNullable}";
41 }
42}Download full source code.