2014-09-04 73 views
0

我正在开发一个带有最新.NET Framework和C#的Web Api 2服务。在同一个控制器上,GET和POST可以工作,但PUT不需要

我有这些方法的控制器:

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

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

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

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

这是WebApiConfig类:

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

当我尝试做api/Users/4一个PUT我得到一个错误,告诉我,这只是允许GET。这是我做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'."} 

你知道我为什么得到这个错误吗?

+0

_“一个错误告诉我,它只允许GET”_ - 显示** actual **错误。或者说,研究它。 – CodeCaster 2014-09-04 08:58:44

+0

我已更新我的问题。 – VansFannel 2014-09-04 10:10:51

+0

您是否将PUT动词映射到IIS/Web.config中的ExtensionlessUrlHandler(它应该在那里默认情况下我认为,但检查很好)。 – 2014-09-04 11:57:50

回答

2

这是因为您的操作定义为采用参数名称为userId的用户标识,但您的路由设置为使用{id}。它应该是:

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

我从未在一百万年内认为这是问题所在。 – VansFannel 2014-09-04 13:08:46

+0

容易被忽略;) – 2014-09-04 13:23:30

相关问题