ASP.NET Core Web API: Routing by method name?

前端 未结 3 1080
感动是毒
感动是毒 2021-02-15 16:25

I remember from ASP.NET Web API that it\'s sufficient to prefix Web API REST method names with HTTP commands (e.g. GetList() => HTTP GET, Delete(

3条回答
  •  借酒劲吻你
    2021-02-15 17:07

    Neither could we do action overloads nor prefix action name as Http verb.The way routing works in ASP.NET Core is different than how it did in ASP.NET Web Api.

    However, you can simply combine these actions and then branch inside, since all params are optional if you send as querystring

    [HttpGet]
    public ActionResult Get(int id, string name)
    {
      if(name == null){..}
      else{...}
    }
    

    Or you need to use attribute routing to specify each api if you send in route data:

    [HttpGet("{id}")]       
    public ActionResult Get(int id)
    {
        return "value";
    }
    
    
    [HttpGet("{id}/{name}")]
    public ActionResult Get(int id, string name)
    {
        return name;
    }
    

    Refer to Attribute Routing,Web Api Core 2 distinguishing GETs

提交回复
热议问题