我正在使用最新的.NET Framework和C#开发Web Api 2服务。
我有一个带这些方法的控制器:
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 :(得分:2)
这是因为您的操作定义为使用参数名称userId
获取用户ID,但您的路由设置为使用{id}
。它应该是:
public void Put(int id, User user)
{
// ...
}