代码之家  ›  专栏  ›  技术社区  ›  xChaax

如何在webapi URL中动态指定查询字符串

  •  0
  • xChaax  · 技术社区  · 7 年前

     public class peopleController : ApiController
     {
         [HttpGet]
         public IHttpActionResult getAllPeople(string Name, string Age)
         {
            //Return something
         }
     }
    

    我的WebApiConfig是这样的:

    config.Routes.MapHttpRoute(
                name: "getAllPeopleApi",
                routeTemplate: "people",
                defaults: new { controller = "people", action = "getAllPeople" }
    
            );
    

    http://localhost:xxx/people?Name=&Age= . 它工作得很好。

    http://localhost:xxx/people http://localhost:xxx/people?Name= , http://localhost:xxx/people?Age=

    我收到了这个错误信息:

    {"Message":"No HTTP resource was found that matches the request URI 'http://localhost:xxxx/......'.","MessageDetail":"No action was found on the controller 'people' that matches the request."}
    

    routeTemplate: "people/{Name}/{Age}" Error 404.0 Not Found

    2 回复  |  直到 7 年前
        1
  •  0
  •   Freek W.    7 年前
    routeTemplate: "people/{Name}/{Age}"
    

    这部分不是查询字符串,而是动态路径。 这意味着你的道路 Domain/people/SomeName/SomeAge?QueryString=Whatever

        2
  •  0
  •   xChaax    7 年前

    通过显式设置参数解决了这个问题 Name Age Null .

    public class peopleController : ApiController
     {
         [HttpGet]
         public IHttpActionResult getAllPeople(string Name = null, string Age=null)
         {
            //Return something
         }
     }
    

    这将使参数成为可选参数。现在可以使用或不使用查询字符串参数调用控制器。

    推荐文章