Web API 2 - Method now allowed(405) for PUT

妖精的绣舞 提交于 2020-03-27 02:53:38

问题


I am stuck with Web API 2 controller, from which I call PUT method and it gives me an error that method isn't allowed. I added lines of code in Web.config that prevent WebDAV to block methods. I tried everything but it is not working. It is probably problem with my PUT method in a controller.

Here is my controller code:

public IHttpActionResult Put(int id, [FromBody]ArticleModel model) {
    var article = _articleService.UpdateArticle(model);
    return Ok<ArticleModel>(article);
}

This is a code from where I call put :

  response = await client.PutAsJsonAsync("api/article/2", articleModel);

before this code I defined client as http and added needed properties, and called other controller methods (GET, POST, DELETE) , they all work. This is from Windows Form app, and I am also calling from Postman but still the same error.


回答1:


Add [HttpPut] , [RoutePrefix("api/yourcontroller")] and [Route("put")] attribute to your controller method

Example:

[RoutePrefix("api/yourcontroller")]
public class YourController
{
 [HttpPut]   
 [Route("{id}/put")]
 public IHttpActionResult Put(int id, [FromBody]ArticleModel model) {
   var article = _articleService.UpdateArticle(model);
   return Ok<ArticleModel>(article);
 }
}

EDIT 1

public class YourController
{
 [HttpPut]   
 [Route("api/article/{id}/put")]
 public async Task<HttpResponseMessage> Put(int id, [FromBody]ArticleModel model) {
   var article = _articleService.UpdateArticle(model);
   return Ok<ArticleModel>(article);
 }
}

From your HttpRequest call It seems what is expected is a HttpResponseMessage So changed the return type to async Task<HttpResponseMessage>

Code for making HttpRequest:

response = await client.PutAsJsonAsync("api/article/2/put", articleModel);



回答2:


Add the [System.Web.Http.HttpPut] attribute to your method.



来源:https://stackoverflow.com/questions/37917372/web-api-2-method-now-allowed405-for-put

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!