简体   繁体   中英

How to route using [HttpGetAttribute] including the query strings in AspNet.Core WebApi application?

I have the following routing, which works on invokation /api/demo/info/34 .

[Route("api/demo")]
public class Demo : Controller
{
    [HttpGet("Info/{x}")]
    public JsonResult GetInfos(string x) { ... }
}

Now, I'd like to pass a query string to select the ID, like so: /api/demo/info?x=34 . How should I rephrase the attribute for that?

When I tried entering [HttpGet("Info?x={x}")] , the error message said that the question mark isn't valid there. I want to resolve it through the attributive approach and routing from the default mapping isn't an option.

All you should need to do is to declare your attribute as:

[HttpGet("Info")]

while keeping the signature of the method as GetInfos(string x) . In a GET route, WebAPI picks up all the parameters from the signature, and those which aren't present in the route can be passed as query string arguments as long as the name in the query string matches the name of the parameter.

Just remove the parameter from the route and the framework will interpret it based on the action's parameters.

[Route("api/demo")]
public class Demo : Controller {
    //GET api/demo/info?x=34
    [HttpGet("Info")]
    public JsonResult GetInfos(string x) { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM