【问题标题】:How to dynamically specify Query String in Web API URL如何在 Web API URL 中动态指定查询字符串
【发布时间】:2018-09-13 11:56:32
【问题描述】:

我是 c# 和 web api 的新手。我有一个带有 Get 方法的 WebAPI 控制器,如下所示:

 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}"。现在当我运行这个 web api Error 404.0 Not Found

【问题讨论】:

    标签: c# asp.net-web-api routes


    【解决方案1】:
    routeTemplate: "people/{Name}/{Age}"
    

    这部分不是QueryString,这是一个动态路径。 这意味着你的路径变成了Domain/people/SomeName/SomeAge?QueryString=Whatever

    【讨论】:

    • 感谢@Freek W. 的澄清。对于查询字符串,我可以根据我的问题实现吗?
    • QueryString 始终是 URL 中 ? 指示符之后的最后一部分。您可以使用Request.QueryString["AttributeNameHere"] 调用控制器中的查询字符串。我不确定这是您问题的答案,请详细说明您的问题。
    • 如果我像这样运行我的 webApi http://localhost:xxx/people?Name=&Age= 我会得到响应。如果我删除参数NameAge 中的两个或其中之一,就像http://localhost:xxx/people 得到错误不是没有找到 Http 资源。这对你来说清楚吗?
    • 那是因为刚才domain/people不是路由(不存在),路由明确domain/people/{Name}/{Age}(只有存在),这两个动态项需要满足才能查找页面的请求。不过,这个问题仍然不是很清楚,您是想将查询字符串添加到控制器中的某些东西,还是想动态地将值添加到您的路由中?你想完成什么?
    • 好的,我的问题是如何在 URL 中动态指定我的查询字符串。现在什么时候这样做http://localhost:xxx/people?Name=&Age= OK。什么时候喜欢这些 3 http://localhost:xxx/people,http://localhost:xxx/people?Name=,http://localhost:xxx/people?Age= 不行。你说清楚了吗?
    【解决方案2】:

    通过将参数NameAge 显式设置为Null 来解决此问题。

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

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

    【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2018-08-07
    相关资源
    最近更新 更多