Ingmar
Ingmar

Reputation: 1457

Routing: How to allow Path parameters and Query parameters at the same time?

For my ASP.NET Core 6.0 MVC web application, I need both:

http://example.com/users/7 and
http://example.com/users?userid=7

My current controller looks like this:

    [HttpGet("users/{userId}")]
    public IActionResult GetUser(int userId)
    { ... }

The first call works, the second returns a 404.

I wonder why... and what do I need to do to fix this (allow both calls)?

Upvotes: 0

Views: 1610

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11939

userId section is required so the second Url returned 404

You could try add ? to set Userid section nullable as below:

 [Route("Users/{UserId?}")]
            public IActionResult GetUser(int UserId)
            {
                return Ok();
            }

Result:

enter image description here

Upvotes: 2

Related Questions