VansFannel
VansFannel

Reputation: 46041

At the same controller, GET and POST works, but PUT don't

I'm developing a Web Api 2 service with latest .NET Framework and C#.

I have a controller with these methods:

public IEnumerable<User> Get()
{
    // ...
}

public User Get(int id)
{
    // ...
}

public HttpResponseMessage Post(HttpRequestMessage request, User user)
{
    // ...
}

public void Put(int userId, User user)
{
    // ...
}

And this is WebApiConfig class:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

When I try to do a PUT on api/Users/4 I get an error telling me that it only allows GET. This is the response when I do a Put:

HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: GET
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcVWljMTguSUNcU291cmNlc1xSZXBvc1xWaWEgQ29nbml0YVxNYXR0XHNyY1xNYXR0LlNvY2lhbE5ldHdvcmsuV2ViLkFwaVxhcGlcVXNlcnNcMQ==?=
X-Powered-By: ASP.NET
Date: Thu, 04 Sep 2014 10:04:26 GMT
Content-Length: 68

{"Message":"The requested resource does not support the method http 'PUT'."}

Do you know why I'm getting this error?

Upvotes: 0

Views: 525

Answers (1)

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26976

It's because your action is defined to take the user id with a parameter name of userId but your routing is set up to use {id}. It should read:

public void Put(int id, User user)
{
  // ...
}

Upvotes: 2

Related Questions