C# 405 方法不允许 Web API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15718741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
405 method not allowed Web API
提问by Xardas
This error is very common, and I tried all of the solutions and non of them worked. I have disabled WebDAV publishing in control panel and added this to my web config file:
这个错误很常见,我尝试了所有的解决方案,但没有一个有效。我在控制面板中禁用了 WebDAV 发布并将其添加到我的 Web 配置文件中:
<handlers>
<remove name="WebDAV"/>
</handlers>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
The error still persists. This is the controller:
错误仍然存在。这是控制器:
static readonly IProductRepository repository = new ProductRepository();
public Product Put(Product p)
{
return repository.Add(p);
}
Method implementation:
方法实现:
public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId++;
products.Add(item);
return item;
}
And this is where the exception is thrown:
这是抛出异常的地方:
client.BaseAddress = new Uri("http://localhost:5106/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/products", product);//405 exception
Any suggestions?
有什么建议?
采纳答案by Darin Dimitrov
You are POSTing from the client:
您正在从客户端发布:
await client.PostAsJsonAsync("api/products", product);
not PUTing.
不放。
Your Web API method accepts only PUT requests.
您的 Web API 方法仅接受 PUT 请求。
So:
所以:
await client.PutAsJsonAsync("api/products", product);
回答by Per Stolpe
This does not answer your specific question, but when I had the same problem I ended up here and I figured that more people might do the same.
这并不能回答你的具体问题,但是当我遇到同样的问题时,我最终来到这里,我认为更多的人可能会做同样的事情。
The problem I had was that I had indeliberately declared my Get method as static. I missed this an entire forenoon, and it caused no warnings from attributes or similar.
我遇到的问题是我无意中将 Get 方法声明为static。我错过了整个上午,它没有引起属性或类似的警告。
Incorrect:
不正确:
public class EchoController : ApiController
{
public static string Get()
{
return string.Empty;
}
}
Correct:
正确的:
public class EchoController : ApiController
{
public string Get()
{
return string.Empty;
}
}
回答by Llad
I had the same exception. My problem was that I had used:
我有同样的例外。我的问题是我曾经使用过:
using System.Web.Mvc; // Wrong namespace for HttpGet attribute !!!!!!!!!
[HttpGet]
public string Blah()
{
return "blah";
}
SHOULD BE
应该
using System.Web.Http; // Correct namespace for HttpGet attribute !!!!!!!!!
[HttpGet]
public string Blah()
{
return "blah";
}
回答by Nexxas
My problem turned out to be Attribute Routing in WebAPI. I created a custom route, and it treated it like a GET instead of WebAPI discovering it was a POST
我的问题原来是 WebAPI 中的属性路由。我创建了一个自定义路由,它把它当作一个 GET 而不是 WebAPI 发现它是一个 POST
[Route("")]
[HttpPost] //I added this attribute explicitly, and it worked
public void Post(ProductModel data)
{
...
}
I knew it had to be something silly (that consumes your entire day)
我知道它一定是愚蠢的(消耗你一整天的时间)
回答by user3963793
[HttpPost] is unnecessary!
[HttpPost] 不需要!
[Route("")]
public void Post(ProductModel data)
{
...
}
回答by user2662006
I tried many thing to get DELETE method work (I was getting 405 method not allowed web api) , and finally I added [Route("api/scan/{id}")]to my controller and was work fine. hope this post help some one.
我尝试了很多方法来让 DELETE 方法工作(我得到了 405 方法不允许 web api),最后我将[Route("api/scan/{id}")] 添加到我的控制器并且工作正常。希望这篇文章对某人有所帮助。
// DELETE api/Scan/5
[Route("api/scan/{id}")]
[ResponseType(typeof(Scan))]
public IHttpActionResult DeleteScan(int id)
{
Scan scan = db.Scans.Find(id);
if (scan == null)
{
return NotFound();
}
db.Scans.Remove(scan);
db.SaveChanges();
return Ok(scan);
}
回答by Sako73
I was getting the 405 on my GET call, and the problem turned out that I named the parameter in the GET server-side method Get(int formId)
, and I needed to change the route, or rename it Get(int id)
.
我在 GET 调用中得到 405,结果问题是我在 GET 服务器端方法中命名了参数Get(int formId)
,我需要更改路由,或者重命名它Get(int id)
。
回答by Nate Zaugg
Chrome often times tries to do an OPTIONS
call before doing a post. It does this to make sure the CORS headers are in order. It can be problematic if you are not handling the OPTIONS
call in your API controller.
Chrome 经常会OPTIONS
在发帖前先打电话。这样做是为了确保 CORS 标头是有序的。如果您不处理OPTIONS
API 控制器中的调用,则可能会出现问题。
public void Options() { }
回答by Tom Stickel
You can also get the 405 error if say your method is expecting a parameter and you are not passing it.
如果说您的方法需要一个参数而您没有传递它,您也可能会收到 405 错误。
This does NOT work ( 405 error)
这不起作用(405错误)
HTML View/Javascript
HTML 视图/Javascript
$.ajax({
url: '/api/News',
//.....
Web Api:
网络API:
public HttpResponseMessage GetNews(int id)
Thus if the method signature is like the above then you must do:
因此,如果方法签名与上述类似,那么您必须执行以下操作:
HTML View/Javascript
HTML 视图/Javascript
$.ajax({
url: '/api/News/5',
//.....
回答by Spencer Sullivan
I could NOT solve this. I had CORS enabled and working as long as the POST returned void (ASP.NET 4.0 - WEBAPI 1). When I tried to return a HttpResponseMessage, I started getting the HTTP 405 response.
我无法解决这个问题。只要 POST 返回 void (ASP.NET 4.0 - WEBAPI 1),我就启用了 CORS 并工作。当我尝试返回 HttpResponseMessage 时,我开始收到 HTTP 405 响应。
Based on Llad's response above, I took a look at my own references.
根据上面 Llad 的回复,我查看了我自己的参考资料。
I had the attribute [System.Web.Mvc.HttpPost] listed above my POST method.
我在我的 POST 方法上方列出了属性 [System.Web.Mvc.HttpPost]。
I changed this to use:
我将其更改为使用:
[System.Web.Http.HttpPostAttribute]
[HttpOptions]
public HttpResponseMessage Post(object json)
{
...
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
This fixed my woes. I hope this helps someone else.
这解决了我的困境。我希望这对其他人有帮助。
For the sake of completeness, I had the following in my web.config:
为了完整起见,我在 web.config 中有以下内容:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>