如何调用Web Api,使用属性路由为每个操作方法实现,从我的客户端调用它并在url中传递Query参数?

时间:2014-06-02 13:11:48

标签: asp.net-web-api

我已经为My Webapi中的每个操作方法实现了属性路由。 动作方法的示例是: -

[Route("api/DocumentApi/DeleteDocument/{fileInfoId}/{customerAccountName}")]
      [HttpDelete]
      public HttpResponseMessage DeleteDocument(int fileInfoId, string customerAccountName)
      {

            //***
            //*** Some body contents
            //***
      }

现在我想从客户端示例(Fiddler Web调试器)或浏览器调用上述操作方法,并希望以下面的模式传递Url请求: -

http://{localhost:9791}/api/DocumentApi/DeleteDocument?fileInfoId=12&customerAccountName="Manish"

目前我无法通过上述指定的网址请求点击上述操作方法。 但如果我使用如下的网址模式: -

http://{localhost:9791}/api/DocumentApi/DeleteDocument/12/Manish

我可以点击上面的操作方法。但是对于我的项目要求,我只需要使用带有查询参数的Url。 请建议我的方法,如何实现这一目标? 任何回复都将不胜感激。

2 个答案:

答案 0 :(得分:2)

Web API中的路径模板不支持指定查询字符串参数。对于您的方案,请不要将fileInfoIdcustomerAccountName定义为路由模板的一部分,因为这样做会使Web API严格查找5个段(路由中/个字符之间的文本)模板)在您的请求网址中...所以只需将您的路线模板修改为[Route("api/DocumentApi/DeleteDocument")]并将参数保留在动作中......

答案 1 :(得分:0)

使用以下代码:

[Route("api/DocumentApi/DeleteDocument/{fileInfoId}/{customerAccountName}")]      
public HttpResponseMessage TestAction(string fileInfoId,string customerAccountName)
{