• web开发中有以下几种情况会出现 405的错误； 1 在前端的请求方式与后台的不匹配： 例如后台通过post方式，而你在前端用get方式则会出现405的错误。这样只要让他们 保持一致就不会报错。 2 在前端提交的请求参数与...
在web开发中有以下几种情况会出现 405的错误；
1 在前端的请求方式与后台的不匹配：
例如后台通过post方式，而你在前端用get方式则会出现405的错误。这样只要让他们
保持一致就不会报错。
2 在前端提交的请求参数与后端不一致：
在很多时候我们会在请求路径后面拼接几个参数，一旦我们拼接的参数与前端控制器中所要接受的
参数不一致（名称不一致或者数目不一致）同样也会报405的错误。
3 请求路径书写不正确有时候也可能会出现405的错误。
展开全文
• 问题的原因：创建webapi controller时，习惯创建了...这两天搞webapi开发的时候，遇见了405错误。 我贴一下解决的方式： controller中添加如下引用。 using System.Net; using System.Net.Http; using System.We
问题的原因：创建webapi controller时，习惯创建了mvc的controller，而非api controller。导致引用包有问题。

这两天搞webapi开发的时候，遇见了405错误。
我贴一下解决的方式：

controller中添加如下引用。

using System.Net;
using System.Net.Http;
using System.Web.Http;

删除

using System.Web.Mvc;

Action头部添加相应的请求方式

[HttpPost]
[HttpGet]
........


展开全文
• 405 method not allowed Web API Ask Question Asked7 years, 1 month ago Active5 months ago Viewed217k times 84 8 This error is very common, and I tried all of the solutions and non of...
405 method not allowed Web API
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:
  <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)
{
}

Method implementation:
 public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId++;
return item;
}

And this is where the exception is thrown:
client.BaseAddress = new Uri("http://localhost:5106/");
var response = await client.PostAsJsonAsync("api/products", product);//405 exception

Any suggestions?
c# asp.net-web-api webdav
edited Nov 28 '19 at 11:04

Luke Girvin
asked Mar 30 '13 at 12:53

Xardas

59

You are POSTing from the client:
await client.PostAsJsonAsync("api/products", product);

not PUTing.
Your Web API method accepts only PUT requests.
So:
await client.PutAsJsonAsync("api/products", product);

answered Mar 30 '13 at 12:58

Darin Dimitrov

59

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

edited May 8 '14 at 7:33

Beatles1692
answered Feb 24 '14 at 21:20

18

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

answered Sep 3 '14 at 3:14

user2662006
For some reason my it was only not working for the delete, for creating and updating it worked fine. Well, I just added [HttpPost] and it worked. But thanks, you got me on the right track and only cost me 5 mins now :) – Rubenisme Jul 15 '16 at 11:52  1 Why aren't you just adding the [HttpDelete] attribute? – johnny 5 Dec 11 '17 at 22:03

12

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
    [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)
answered Aug 14 '14 at 15:39

Nexxas

6

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.
public void Options() { }

answered Jul 3 '15 at 20:48

Nate Zaugg

6

This error can also occur when you try to connect to http while the server is on https.
It was a bit confusing because my get-requests were OK, the problem was only present with post-requests.
edited Feb 6 '18 at 10:24
answered Feb 6 '18 at 10:19

FrankyHollywood
Thanks for your explanation, It worked for me :) – Braytiner Aug 22 '19 at 12:10

4

You can also get the 405 error if say your method is expecting a parameter and you are not passing it.
This does NOT work ( 405 error)
HTML View/Javascript
$.ajax({ url: '/api/News', //.....  Web Api: public HttpResponseMessage GetNews(int id)  Thus if the method signature is like the above then you must do: HTML View/Javascript $.ajax({
url: '/api/News/5',
//.....

answered Sep 3 '15 at 20:37

Tom Stickel
I seem to be running into 405 errors for various reasons, they do all boil down to the fact of it attempting to HIT the method signature and a parameter issue or a convention naming issue or a Attribute issue etc... – Tom Stickel Sep 17 '15 at 5:49

4

If you have a route like
[Route("nuclearreactors/{reactorId}")]

You need to use the exact same parameter name in the method e.g.
public ReactorModel GetReactor(reactorId)
{
...
}

If you do not pass the exact same parameter you may get the error "405 method not allowed" because the route will not match the request and WebApi will hit a different controller method with different allowed HTTP method.
edited Apr 1 '17 at 13:14
answered Apr 1 '17 at 10:42

roylac
This is not an answer either! – Div Apr 1 '17 at 11:08  @Div "405 method not allowed" can be shown in the case I shared because the method will not catch api-call as the route setup is invalid. The api-call may then hit another unintended method which could have a different HTTP action allowed. Yes I agree that this answer may not be 100% relevant for the actual question, however the title of the question by Xardas is not very specific and I believe that many people landing here in search of answers to the question as stated by the title may find this answer useful. – roylac Apr 1 '17 at 13:11

Here is one solution
<handlers accessPolicy="Read, Script"> <remove name="WebDAV" /> </handlers>
docs.microsoft.com solution article
and remove WebDAV from modules
<remove name="WebDAVModule" />

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).

I'm late to this party but as nothing above was either viable or working in most cases, here is how this was finally resolved for me.
On the server the site/service was hosted on, a feature was required! HTTP ACTIVATION!!!

Server Manager > Manage > Add Roles and Features > next next next till you get to Features > Under .NET (each version) tick HTTP Activation. Also note there is one hidden under >net > WCF Services.

This then worked instantly! That was melting my brain

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.
Based on Llad's response above, I took a look at my own references.
I had the attribute [System.Web.Mvc.HttpPost] listed above my POST method.
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:
<httpProtocol>
<clear />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<remove name="X-Powered-By" />
</httpProtocol>


This will have the method called on the OPTIONS pre-flight request (as well as on POST), at which point json is likely null since pre-flight requests usually don't have payloads, or you'll run the post action twice. – glennsl Sep 3 '18 at 20:25

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.
Incorrect:
public class EchoController : ApiController
{
public static string Get()
{
return string.Empty;
}
}

Correct:
public class EchoController : ApiController
{
public string Get()
{
return string.Empty;
}
}


[HttpPost] is unnecessary!
[Route("")]
public void Post(ProductModel data)
{
...
}

answered Aug 21 '14 at 10:39

user3963793
Yes the way that you are doing it is correct in that you do not need an explicit [HttpPost] , however there are some people not following convention (yikes) and thus something like [Route("MyMethodSaver"] public string MyMethodtoSave(int? id) --> that would need a [HttpPost] and it would then work – Tom Stickel Sep 17 '15 at 5:37

1

We had a similar issue. We were trying to GET from:
[RoutePrefix("api/car")]
public class CarController: ApiController{

[HTTPGet]
[Route("")]

}

}

So we would .GET("/api/car") and this would throw a 405 error.

The Fix:

The CarController.cs file was in the directory /api/car so when we were requesting this api endpoint, IIS would send back an error because it looked like we were trying to access a virtual directory that we were not allowed to.
Option 1: change / rename the directory the controller is inOption 2: change the route prefix to something that doesn't match the virtual directory.

check in your project .csproj file and change
<IISUrl>http://localhost:PORT/</IISUrl>

to your website url like this
<IISUrl>http://example.com:applicationName/</IISUrl>


For my part my POST handler was of this form:
[HttpPost("{routeParam}")]
public async Task<ActionResult> PostActuality ([FromRoute] int routeParam, [FromBody] PostData data)

I figured out that I had to swap the arguments, that is to say the body data first then the route parameter, as this:
[HttpPost("{routeParam}")]
public async Task<ActionResult> PostActuality ([FromBody] PostData data, [FromRoute] int routeParam)


Another possible issue which causes the same behavior is the default parameters in the routing. In my case the controller was located and instantiated correctly, but the POST was blocked because of default Get action specified:
config.Routes.MapHttpRoute(
name: "GetAllRoute",
routeTemplate: "api/{controller}.{ext}"/*,
defaults: new { action = "Get" }*/ // this was causing the issue
);

answered Mar 6 '17 at 20:48

0

In my case I had a physical folder in the project with the same name as the WebAPI route (ex. sandbox) and only the POST request was intercepted by the static files handler in IIS (obviously).
Getting a misleading 405 error instead of the more expected 404, was the reason it took me long to troubleshoot.
Not easy to fall-into this, but possible. Hope it helps someone.

I was having exactly the same problem. I looked for two hours what was wrong with no luck until I realize my POST method was private instead of public .
Funny now seeing that error message is kind of generic. Hope it helps!

Make sure your controller inherits from Controller class.
It might even be crazier that stuff would work locally even without that.
展开全文
• 在浏览WEB时，刚进去的登录界面正常，但是点击登录之后就出现错误“应用程序“MYWEBSITE”中的服务器错误” “HTTP 错误 405.0 - Method Not Allowed 无法显示您正在查找的页面，因为使用了无效方法(HTTP 谓词)。” ...
• 405的报错大概就是后端程序没有被允许此次请求，要解决这个问题，就是在后端程序中允许请求通过。具体操作就是修改web.config配置项，如下图所示： 修改后就是这个样子： 添加的配置信息如下： <...
浏览器报错

本来没有报这个错，当我在ajax中添加了请求头信息时报错

405的报错大概就是后端程序没有允许此次请求，要解决这个问题，就是在后端程序中允许请求通过。具体操作就是修改web.config配置项，如下图所示：

修改后就是这个样子：

添加的配置信息如下：


展开全文
• 1、404错误 是服务器执行完客户端的请求以后，返回给客户端的一个执行结果的状态编码。 产生原因：web服务器（容器）根据请求的地址...2、405错误 产生原因：web服务器（容器）找不到service（）方法处理请求。 如：...
• PUT与delete的ajax出现405报错，原因为IIS拒绝PUT和DELETE请求是由于IIS为网站默认注册的一个名为WebDAVModule的自定义HttpModule导致的。 2.解决办法 通过配置weconfig的方式解决该问题 <system.webServer> &...
• 今天在写web时，写了一个ajax请求，但是从fiddler中抓包显示总是返回405状态码。405：表示不允许的请求方法网上查资料，有说是因为发起的post请求中没有携带参数，但是我在post中已经携带参数了后来发现是，我在定义...
• IIS默认不支持PUT调用方式，必须在IIS中找到“处理程序映射”--“WebDAV”--"请求限制"--“谓词”---“全部谓词”---确认，OK
• 1,405 这个是因为重写doGet和doPost方法的时候没有注释掉super.方法 2,。对于jar包 众所周知，放lib下，或者右键或者去buildpath 但是web项目存在多个lib，这里需要放置在WebContent-WEB-INF-lib这里，然后右键...
• Web Api 调用时出现405错误 之前可以调用成功，说明配置没问题 说明： .net core WebApi 在配置终结点时adress不需要指定svc，但是wcf服务需要 错误提示： System.ServiceModel.ProtocolException: The remote ...
• 总结列表： 1. There is already an open DataReader associated with this Connection which must be closed first 2. npm install 失败 ... WebApi HTTP Put 405 Method not allowed 服务器升级了IIS，We...
• .netpost后台（api在iis另一个程序上）会提示405 (Method Not Allowed)和Response for preflight has invalid HTTP status code 405 ...最后才发现,WebApi报405的解决方案应该是修改Web.config(emmm,暂时还不知道...
• 写了个webapi给同事用ajax调用，配置完跨域以后get请求完全没问题，post就一直报405错误，花了半天时间就是解决不了，后来在网上看到一博主的帖子才知道原来是webapi 默认的web.config配置问题，转载过来记录一下以...
• web访问接口报405错误，以前的jQuery访问方式访问接口没有问题。 但是换成angularjs2.0之后调用接口就报405错误，ajax调用没有问题。 查找资料之后找到解决方案： 原因是webapi 默认的web.config有配置 <...
• $("#testBtn").click(function () {$.ajax({ type: "GET", ... dataType: "json", beforeSend: function (request) { ... request.setRequestHeader("pwd", "mkh201605");... error: function (XMLHttpRequest, ...
• webapi打包发布后当发送put、delete等请求时出现405错误码如下图 这个错误是因为服务器不支持该谓词请求 解决方法： 1、在web.config文件中system.webServer节点添加如下配置 <modules ...
• WebAPI测试时，Put请求时提示405错误，错误消息为不支持此页的HTTP谓词。本地测试正常，放到外网服务器报这个错误。检索了一下，按照如下网址的方式解决。 ...
• 当你向服务器发送非简单请求时，客户端会先发送一条预检请求，借以确认当前请求源和待请求方法是否被网站允许。但是在IIS寄宿的Web API 2.0网站中，Options请求会得到405返回码。本文提供了这个问题的解决思路
• nuget控制台敲入以下命令:Install-Package Microsoft.AspNet.WebApi.Cors –IncludePrerelease打开WebApiConfig.cs添加如下红色标注行 public static void Register(HttpConfiguration config) {// Web API ...
• org.springframework.web.client.HttpClientErrorException: 405 null at org.springframework.web.client 排查了下原因 造成错误的原因：controller层请求 是标识 RequestMethod.POST的请求 @RequestMapping(value ...
• 本地完全没问题，但是当发布到服务器上之后（IIS7.5），就报出 405.0 - Method Not Allowed 很明显是配置问题。 经过查找资料找到解决方法：在Web.config中添加一段配置 <system.webServer> <modules ...
• 最近在做一个WebAPI和Vue案子，本机调试没有问题，但发布到IIS服务器上，报错返回405,500. 确认是在put请求时发生。度娘了很多文章没有同时解决问题，后参考其它案子的写法，在web.config内增加以下内容，即可解决。...
• webapi webconfig里添加节点
• 在IDEA中创建了一个form表单，点击提交按钮使用...@WebServlet("/userServlet") public class UserServlet extends HomeServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp)
• 作为新手容易出现的错误，出错的代码截图 ...请求后返回405的截图 问题的原因及解决方法： HttpServlet类的doGet方法代码： 所以只要把super.doGet(req.resp);这行代码删除或注释掉就行了 ...

...