如何修复 - 请求的资源不支持 http 方法 'POST'

How to fix - The requested resource does not support http method 'POST'

以下是 WebAPI 操作。在谷歌上搜索以下错误:-

The requested resource does not support http method 'POST'

我得到了链接数并相应地更新了我的 api 但我仍然遇到同样的错误。

但是当通过 post 调用上面的方法时仍然会抛出错误。

如何摆脱这个错误?

是否可以在不使用方法参数列表中的 [FromBody] 属性的情况下解决此问题?

任何 help/suggestion 高度赞赏。 谢谢。

您已声明需要 url 个参数的路由

[Route("rename/{userId}/{type}/{title}/")]

所以当你向api/customer/rename发送请求时,它不匹配这个方法。您应该从路由参数中删除您在请求正文中传递的参数

[Route("rename")]

确保您的控制器具有适当的 RoutePrefix("api/customer") 属性。


第二个问题是多个 [FromBody] 参数。你会得到 can't bind multiple parameters 错误。存在限制 - 您只能将一个参数标记为 FromBody。参见 Sending Simple Types 注释:

Web API reads the request body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

您应该创建包含所有参数的复杂类型

public class RenameModel
{
   public int UserId { get; set; }
   public string Type { get; set; }
   public string Title { get; set; }
}

并将方法签名更改为

[HttpPost]
[Route("rename")]
public IHttpActionResult Rename(RenameModel model)

并将请求数据发送为application/x-www-form-urlencoded

 [Route("rename/{userId}/{type}/{title}/")]
 public IHttpActionResult Rename([FromBody] int userId,  [FromBody] string  type, [FromBody] string title)

最后一个答案是正确的,你在路由中要求这些参数,但说你希望它们在 post 正文中。此外,通常路线会以名词而不是动词开头。你重命名的是什么? (即 [路线("users/rename/{userId}/{type}/{title}")]

根据您最初的 post,试试这个:

 [HttpPost]
 [Route("rename/{userId}/{type}/{title}" Name = "RenameUser"]
 public IHttpActionResult Rename(int userId, string type, string title)
 {
     _myServiceMethod.Rename(userId, type, title);
     return new StatusCodeResult(HttpStatusCode.Created, this);   
 }

或者,如果您想对正文中的信息执行 post: 声明您的数据合同:

public class User
{
    public string Type { get; set; }
    public string Title { get; set; }
}

然后在端点上:

[HttpPost]
[Route("rename/{userId}", Name = "RenameUserPost")]
public IHttpActionResult RenameUserPost(int userId, [FromBody] User userData)
{
    return new StatusCodeResult(HttpStatusCode.Created, this);
}

请注意,在两个 return 中,'this' 指的是继承自 ApiController 的控制器 class。大摇大摆地验证了这两个,他们接受 POST 和 return 状态代码。

希望这对您有所帮助。