我有一个 Web API 项目,但我无法针对它启用“PUT/Patch”请求。
我从 fiddler 得到的响应是:
HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: GET,POST,DELETE
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?QzpcUHJvamVjdHNcZG90TmV0XFdlYkFQSVxBZFNlcnZpY2VcQWRTZXJ2aWNlXGFwaVxpbXByZXNzaW9uXDE1?=
X-Powered-By: ASP.NET
Date: Tue, 06 May 2014 14:10:35 GMT
Content-Length: 72
{"message":"The requested resource does not support http method 'PUT'."}
根据上述响应,不接受“PUT”动词。但是,我无法弄清楚相关处理程序的配置位置。
类的“Put”方法声明如下:
[HttpPatch]
[HttpPut]
public HttpResponseMessage Put(Int32 aID, [FromBody] ImpressionModel impressionModel)
{
bla, bla, bla, bla
}
我已阅读并实现了以下线程中解释的更改: - Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings - http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications
尝试对我的 Web API 项目发出“PUT”命令时,我仍然收到 405 响应,但没有任何效果。
我什至注释掉了 ApplicationsHost.config 文件中的所有“处理程序”。
使用 VS2012 Premium 和 IIS Express(我假设它是版本 8)。我也尝试了 VS Dev Server,但结果也一样。
我没主意了。任何帮助将不胜感激。
谢谢李
最佳答案
你在使用属性路由吗?
这个神秘错误是一个路由属性问题。这在您的 WebAPIConfig 中启用为:
config.MapHttpAttributeRoutes();
事实证明,Web Api Controller “无法承载基于动词的 Action 方法和传统 Action 名称路由的混合体。”; https://aspnetwebstack.codeplex.com/workitem/184
简而言之:我需要在我的 API Controller 中使用 [Route] 属性标记我的所有操作,否则在尝试通过传统路由定位时操作是“隐藏的”(405)。
API Controller :
[RoutePrefix("api/quotes")]
public class QuotesController : ApiController
{
...
// POST api/Quote
[ResponseType(typeof(Quote))]
[Route]
public IHttpActionResult PostQuote(Quote quote)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Quotes.Add(quote);
db.SaveChanges();
return CreatedAtRoute("", new { id = quote.QuoteId }, quote);
}
注意:我的路线未命名,因此 CreatedAtRoute() 名称只是一个空字符串。
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
希望对你有帮助
关于c# - Web API - 405 - 请求的资源不支持 http 方法 'PUT',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502198/