4

I have a simple model as that has 2 fields and with the following put method, i'm tring to update it in the db. Everymethod including delete works, however put method always returns a 405 error in Postman. (tried WebDAV solutions as well.) What am I missing here?

enter image description here

PUT METHOD:

{
    "MasterId":1,
    "MasterName":"Test"
}

Action

[HttpPut("{id:int}")]
public async Task<IActionResult> PutMaster(int id, Master master)
{
    if (id != master.MasterId)
    {
        return BadRequest();
    }

    //...some code
    return NoContent();
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Sin5k4
  • 1,556
  • 7
  • 33
  • 57
  • 4
    First observation is that the called URL does not match the route template of the controller action. – Nkosi Nov 24 '19 at 11:12

5 Answers5

12

If you are using IIS to run your application and have WebDav module, that can be an issue. For some strange reason WebDav does not allow PUT.

I just uninstalled it, and it helped.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
7

If your application is being hosted under IIS, running API in ASP.NET Core, include this line in the Web.Config file

<configuration> 
    <system.webServer>
        <modules>
             <remove name="WebDAVModule" />
        </modules>
    </system.webServer>
</configuration>
César Augusto
  • 593
  • 1
  • 7
  • 7
6

Using the [HttpPut("{id:int}")] route attribute, you will need to refer your api with: http://localhost:5000/api/masters/{id}

In your exmample:

PUT http://localhost:5000/api/masters/1

So the id in the param also not needed:

[HttpPut("{id:int}")] 
public async Task<IActionResult> PutMaster(Master master)

And it is a bad practice to expose entity framework object to the client, you should use a DTO class and map it to the entity framework object.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
2

First observation is that the called URL

api/masters

does not match the route template of the controller action [HttpPut("{id:int}")] which would map to a URL like

api/masters/{id:int}

Call the correct URL that matches the action's route template

PUT api/masters/1

The error itself is because most likely you have another route that matches the provided URL but not the HTTP Verb. like a root [HttpGet] on one of the controller actions. This explains why you get a 405 Method Not Allowed error and not a 404 Not Found error

Nkosi
  • 235,767
  • 35
  • 427
  • 472
1

Your method should be

 [HttpPut("{id:int}")]
        public async Task<IActionResult> PutMaster(int id,[FromBody]  Master master)
{}

You need to add [FromBody] attribute in the method.

Request url should be

PUT api/masters/1
MesutAtasoy
  • 772
  • 2
  • 13
  • 24