0

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.

  • I think you just mixed up `Post` and `Put`. You can indeed use the same action for both verbs, but I personally think this is not a good practice in a web application (Post is there to create a new entity, Put should be used to update it). However, you can use both verbs to access the action. For an example there's [this link](https://www.exceptionnotfound.net/using-http-methods-correctly-in-asp-net-web-api/). – Carsten Jun 20 '16 at 08:11
  • It is Put, i made typo .. :( – Miloš Samardžić Jun 20 '16 at 08:16
  • How are you creating your `PUT` request? Through a custom client? Through a web page? Through a dev tool like Postman/Fiddler? – Damien_The_Unbeliever Jun 20 '16 at 08:26
  • Calling from Postman....but from Windows Form application too and still the same error – Miloš Samardžić Jun 20 '16 at 08:31

2 Answers2

2

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);
Pushpendra
  • 1,694
  • 14
  • 27
1

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

Nasreddine
  • 36,610
  • 17
  • 75
  • 94