【问题标题】:Web API QueryString not passing second parameter to controller/actionWeb API QueryString 未将第二个参数传递给控制器​​/操作
【发布时间】:2014-02-27 17:02:45
【问题描述】:

我有一个 Web API 应用程序,它预计会为患者返回一个临床警报列表。使用以下 URL 调用请求

http://myserver:18030/api/Alerts/search?systemId=182&patientId=T000282L

其中 systemId 确定与患者 ID 值相关的临床信息系统。路由在WebApiConfig.cs中设置如下

public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
           name: "Alertsapi",
           routeTemplate: "api/Alerts/search",
           defaults: new { controller = "Alerts" , action = "search"}
       );

控制器动作如下:

    [ActionName("search")]
    public  List<Alert> GetAlerts(string systemId = "", string patientId = "")
    {
        var alerts = from a in db.Alerts
                    where a.alertAuthorReference.Equals(systemId)
                    where a.alertSubjectReference.Equals(patientId)
                    select a;
        return alerts.ToList();
    }

我的印象是 QueryString 参数会自动映射到操作方法参数,但在此示例中,patientId 始终为 null(或我默认提供的空字符串)。我尝试在 action 方法内的代码中读取 QueryString,但它只有一个具有 key systemId 的成员。

为什么不传递第二个参数?

我可以通过使用 patientId=182:T000282L 的 QueryString 然后解析这个复合键来解决它,但我希望最终能够搜索多个参数,因此可能需要访问第三个甚至第四个值来自查询字符串。

【问题讨论】:

  • 如果从GetAlerts() 参数中删除默认值会怎样?
  • 如果我这样做,参数为空
  • 两个参数,或者只是patientId?
  • 第二个。如果我颠倒 URL 中参数的顺序,它仍然是第二个为空的参数。
  • 此时,我建议尝试一个简单的项目,确保多个参数在那里工作,然后添加您的自定义路由和操作属性。从this 之类的内容开始。

标签: c# query-string asp.net-web-api


【解决方案1】:

你需要为类似定义一个路由

 routes.MapHttpRoute(
             name: "GetPagedData",
             routeTemplate: "api/{controller}/{action}/{pageSize}/{pageNumber}"
        )

你的控制器会像

[HttpGet]
("GetPagedResult")]
HttpResponseMessage GetPagedResult(int StartIndex, int PageSize)
{
         // you can set default values for these parameters like StartIndex = 0 etc.
}

【讨论】:

  • 这将需要一个 URL,例如 http://myserver:18030/api/Alerts/search/182/T000282L 才能使用我原来的示例。我希望灵活地搜索多个参数。例如,我可能想要搜索姓名和出生日期,例如 ?surname=Jones&amp;forename=Fred&amp;dob=19450401,并且我不想为每个搜索参数组合配置单独的路线。
  • 你为什么不使用自定义对象,比如创建一个具有 10 个参数的类 SearchFilter,默认情况下应该为 null,而你的函数只需接收该对象并检查给出了哪些参数并填写该对象来自 jquery 并作为数据传递检查此链接techbrij.com/pass-parameters-aspdotnet-webapi-jquery 也检查此habrahabr.ru/post/164945
【解决方案2】:

您现在可以通过 Web API 2 和属性路由轻松获得所需的内容。

看看这篇文章:

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

首先您需要编辑 WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

[...]

在您的情况下,您可以在控制器中测试它是否适用:

    [Route("search")]
    [HttpGet]
    public string search(string systemId = "", string patientId = "")
    {

        return patientId;
    }

并称之为:

http://myserver:18030/search?systemId=182&patientId=T000282L

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多