Own Enum in route param, is it possible?

Viewed 4357

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

3 Answers

Please refer this documentation: https://docs.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.

public enum EnumReviewStatus
{
    Overdue = 4,
}

public IActionResult Index(EnumReviewStatus? statusFilter = null)

url Index?statusFilter=Overdue is work

try this one.

[HttpGet("Sow/{id}/{grain}")]
public IActionResult Sow( int id , Grain grain = Grain.none) { }
Related