5

I have a simple Api function:

// POST: api/Cultivation/Sow/1/5
[HttpGet("Sow/{grain}/{id}")]
public IActionResult Sow(Grain grain, int id) { }

My enum looks like this:

public enum Grain
{
    None,
    Rice,
    Corn,
    Oats
}

My question is, is it possible to get Grain or any enum from Route? When Yes, how to do it?

If No, how to "find" enum by int in elegant way, without if statements etc? Because if myWebapi cant take enums, it is easy to do by simple int

michasaucer
  • 4,562
  • 9
  • 40
  • 91
  • 1
    Check this out :) https://stackoverflow.com/questions/42254852/asp-net-mvc-enum-argument-in-controller-mapping – Ivan Kaloyanov Jan 12 '19 at 15:20
  • Thanks, it is really helpful, but im looking easy way to do it by attributes because i looking for easy setup way for it. If it is impossible to get enum by simple `Route` attribute, i will go for `int` ;) – michasaucer Jan 12 '19 at 15:22
  • Simple cast like `(Grain)grain` works – michasaucer Jan 12 '19 at 15:27

3 Answers3

1

Please refer this documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.2#use-routing-middleware

Hope this helps.

You can add url as you shown

app.UseMvc(routes =>
{
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{grain=somedefault}/{id?}");
});

Tokens within curly braces ({ ... }) define route parameters that are bound if the route is matched. You can define more than one route parameter in a route segment, but they must be separated by a literal value. For example, {controller=Home}{action=Index} isn't a valid route, since there's no literal value between {controller} and {action}. These route parameters must have a name and may have additional attributes specified.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
0
public enum EnumReviewStatus
{
    Overdue = 4,
}

public IActionResult Index(EnumReviewStatus? statusFilter = null)

url Index?statusFilter=Overdue is work

Alexandr Sulimov
  • 1,894
  • 2
  • 24
  • 48
0

try this one.

[HttpGet("Sow/{id}/{grain}")]
public IActionResult Sow( int id , Grain grain = Grain.none) { }
  • Be careful about this - Only one action using an enum can exist. If you try 2 or more actions with different enums it will not work and result in a 500 error. – PKCS12 Apr 04 '22 at 16:36