How to do conditional routing in asp.net core?

1.3k Views Asked by At

I'd like to create routings like below

[HttpPost("device/{id}/disable")]
[HttpPost("device/{id}/enable")]
public async Task SetDevice(stirng id, bool state)

And when the user hit the "device/{id}/disable", the state var will automatically assigned with false, and vise versa. How can I achieve that? Thanks

1

There are 1 best solutions below

1
Mohammad Barbast On BEST ANSWER

You have two options or maybe more:

Use route names:

[HttpPost("device/{id}/disable", Name = "disable_device")]
[HttpPost("device/{id}/enable", Name = "enable_device")]
public async Task SetDevice(stirng id){
   //...
   //get current route name here and implement your logic
   //...
{

If you want to know how to get the route name in your action or razor view see get current route name.

Or use default route values:

[HttpPost("device/{id}/disable/{state=false}")]
[HttpPost("device/{id}/enable/{state=true}")]
public async Task SetDevice(stirng id, bool state){
   //...
{