简体   繁体   中英

.netcore PUT method 405 Method Not Allowed

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?

在此处输入图片说明

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();
}

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.

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.

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM