Asp.net core 3.1 Replace Slash (/) by question Marq (?) in the Url

Viewed 353

In an Asp.net core 3.1 we want to configure the routing.

We have a GetDepart action

[HttpGet("GetDepart/{id}")]
public async Task<ActionResult<Depart>> GetDepart(int id)
{
    //Return a Department
}

How to configure routing to replace slashes (/) with question Mark (?) In Url,

therefore instead of having http://localhost:44339/Departs/GetDepart/1, we want to have http://localhost:44339/Departs/GetDepart ?id=1

2 Answers

You're probably looking for Sources.

Something like this should get you where you want to be ...

[HttpGet("GetDepart")]
public async Task<ActionResult<Depart>> GetDepart([FromQuery] int id)
{
    //Return a Department
}

Notice the [FromQuery] attribute on the id parameter.

HttpGetAttribute need template parameter,but template cannot contain the '?' character,it is by design. So if you want to use ?id=1,you can use like this(but this way is different from route,When http://localhost:44339/Departs/GetDepart it can also go to the action):

[HttpGet("GetDepart")]

    public async Task<ActionResult<Depart>> GetDepart(int id)
    {
        //Return a Department
    }

You don't need to add [FromQuery] before int id,model binding will find it in query string by default.You can refer to official document of model binding.

Related