【问题标题】:Web API Controller is not recognizing newly added methodsWeb API 控制器无法识别新添加的方法
【发布时间】:2016-04-21 15:47:54
【问题描述】:

我正在向其他 Web API 控制器添加方法。测试我能够达到我的断点的现有方法之一。但是,如果我尝试调用其中一个新的,我会得到 404。我正在使用 IIS Express 和 Postman 进行本地测试。下面的例子,你知道是什么原因造成的吗?

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

    {"Message":"No HTTP resource was found that matches the request URI 'http://localhost:53453/api/nisperson/addnewconnection'.",
"MessageDetail":"No action was found on the controller 'NISPerson' that matches the request."}

现有方法:

[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

【问题讨论】:

  • 您在 addnewconnection 周围缺少“”
  • 在实际代码中添加了引号。我在将问题添加到 StackOverflow 时创建了一个类型。
  • 在声明路由时,我通常使用完全限定的路由 [ActionName("ReIndex")] [Route("api/autocomplete/reindex")]
  • 可以肯定的是,您是否完全回收了 IIS Express? (有时它会让应用程序的旧实例在内存中运行......)
  • 那个我没做过,让我试试。我认为在使用 IIS express 时没有必要这样做。

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


【解决方案1】:

您在方法签名中定义了三个必需参数(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(保留您的方法不变)实际上是以下 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 访问您的方法。

【讨论】:

  • 谢谢!我已经习惯了传入 Model 对象,以至于我没有意识到这是简单类型所必需的。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多