Web API Controller无法识别新添加的方法

时间:2016-04-21 15:47:55

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

我正在向其他Web API控制器添加方法。测试我现有的一种方法,我能够达到我的突破点。然而,如果我尝试调用其中一个新的,我会得到404.我在本地使用IIS Express和Postman进行测试。以下示例,任何可能导致这种情况的想法?

当我尝试调用新端点时,这是我收到的响应:

[HttpPost]
[ActionName("register")]
public ClientResponse PostRegisterPerson(HttpRequestMessage req, PersonModel person)
{
  // This method is getting hit if I call it from Postman
}

现有方法:

http://localhost:53453/api/test/register

端点: [HttpPost] [ActionName("addnewconnection")] public ClientResponse PostNewConnection(HttpRequestMessage req, string Email, String FirstName, string LastName) { // This is the new method which when called from Postman cannot be found. }

新增方法:

http://localhost:53453/api/test/addnewconnection

终点: {{1}}

2 个答案:

答案 0 :(得分:2)

您在方法签名中定义了三个必需的参数(EmailFirstNameLastName):

[HttpPost]
[ActionName("addnewconnection")]
public ClientResponse PostNewConnection(HttpRequestMessage req, string Email, String FirstName, string LastName)
{
  // This is the new method which when called from Postman cannot be found. 
}

路由处理程序无法将此URI:http://localhost:53453/api/test/addnewconnection映射到您的方法,因为您没有提供这三个必需参数。

正确的URI(保留您的方法)实际上是以下一个:

http://localhost:53453/api/test/addnewconnection?Email=foo&FirstName=bar&LastName=baz

如图所示在URI中提供这些参数,或者将它们视为不需要提供默认值:

[HttpPost]
[ActionName("addnewconnection")]
public ClientResponse PostNewConnection(HttpRequestMessage req, string Email = null, String FirstName = null, string LastName = null)
{
  // This is the new method which when called from Postman cannot be found. 
}

提供默认值将允许您使用原始URI命中方法。

答案 1 :(得分:1)

原因是它期望在您不提供的查询字符串中提供其他参数(简单字符串类型)。因此,它试图使用单个参数调用Post并且无法找到它。默认情况下,简单类型从URI读取。如果您希望它们从表单主体中读取,请使用FromBody属性。