ASP.NET Core 6 Web API / C# : routing, POST method, how to set default param

125 views Asked by At

Set routing at top of controller:

[Route("api/import/v1")]
[ApiController]
public class ImportController : ControllerBase
{
     // .....
}

And setting it on a test function:

[AllowAnonymous]
[HttpPost("{id1}/{id2}/{id3}")]
public ActionResult Test(string id1, string id2, string id3)
{
     // .....
}

In Postman, if I call:

https://localhost:7045/api/import/v1/111/222/333

it hits the POST method and all is well.

However if the id3 string param is optional how can I set a default value on this?

I have tried:

[AllowAnonymous]
[HttpPost("{id1}/{id2}/{id3?}")]
public ActionResult Test(string id1, string id2, string? id3 = "000")
{
     // .....
}

and calling

https://localhost:7071/api/import/v1/111/222/null

but id3 is being set as null.

I also tried

[AllowAnonymous]
[HttpPost("{id1}/{id2}/{id3}")]
public ActionResult Test(string id1, string id2, string? id3 = "000")
{
     // .....
}

but I get the same result - id3 is passed in as null.

Any ideas please?

UPDATE UPDATE UPDATE Just for testing purposes I have added a new function

[AllowAnonymous]
[HttpPost("Test2")]
public ActionResult Test2(string id1, string id2, string? id3 = "000")
{
  // .....
}

If I then use postman to call https://localhost:7045/api/import/v1/Test2?id1=111&id2=111&id3=

this will return as expected id1 = 111 id2 = 111 id3 = 000

but when I try to call

https://localhost:7071/api/import/v1/111/222/

I am getting a 404 Not Found

why would it not be working when I try to use routing?

0

There are 0 answers