Mvc-Web API: 405 Method Not Allowed

405 method not allowed Web API

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

405 method not allowed - ASP.NET Web API

It works for ValuesController because the convention-based route template...

"api/{controller}/{id}" 

has {id} placeholder, which the controller conforms to, while JobDetailController.Delete(int jobId) does not match the route template because of jobId parameter name. Change those parameter arguments to int id in order for it to match route template set by the convention.

[HttpDelete]
public HttpResponseMessage Delete(int id) {
//...
}

Otherwise you could instead use attribute routing as it is also enabled with config.MapHttpAttributeRoutes()

Reference: Attribute Routing in ASP.NET Web API 2

[RoutePrefix("api/JobDetail")] 
public class JobDetailController : ApiController {

[HttpGet]
[Route("")] //Matches GET api/jobdetail
public IEnumerable<JobDetail> Get() {
//...
}

[HttpGet]
[Route("{id:int}")] //Matches GET api/jobdetail/1
public HttpResponseMessage Get(int id) {
//...
}

[HttpGet]
[Route("{locationName}")] //Matches GET api/jobdetail/somewhere
public HttpResponseMessage RetrieveJobByLocation(string locationName) {
//...
}

[HttpDelete]
[Route("{jobId:int}")] //Matches DELETE api/jobdetail/1
public HttpResponseMessage Delete(int jobId) {
//...
}
}

Note that when routing to a controller it is either by convention or by attribute, not both. If routing by attribute to an action, then all the other actions on the controller need attribute routing as well.

405 error (Method Not Allowed) on Web API get

As mentioned in one of the other answers, the code configured the wrong routes. For web api configure the WebApiConfig

public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API routes

//Enable Attribute routing is they are being used.
config.MapHttpAttributeRoutes();

//Convention based routes.

//Matches GET /api/FavoriteArticles/SetFavorite
config.Routes.MapHttpRoute(
name: "DefaultActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

//Matches GET /api/FavoriteArticles
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

Make sure that it is configured before MVC routes.

protected void Application_Start() {
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
//...other configurations
}

Some advice about refactoring the controller to be a little more restful. Try to return IHttpActionResult from actions. simplifies the framework and give you more control of how the response is returned.

[RoutePrefix("api/favoritearticles"]
public class FavoriteArticlesController : BaseController<FavoriteArticle, Guid> {

[HttpPost]
[Route("{articleId:guid}")] //Matches POST api/favoritearticles/{articleId:guid}
public IHttpActionResult SetFavorite(Guid articleId) {
var favorite = new FavoriteArticle
{
UserId = UserInfo.GetUserId(),
ArticleId = articleId
};
_repo.Upsert(favorite);
_repo.Commit();
return Ok(new { Success = true, Error = (string)null });
}

[HttpDelete]
[Route("{articleId:guid}")] //Matches DELETE api/favoritearticles/{articleId:guid}
public IHttpActionResult RemoveFavorite(Guid articleId) {
var favorite = _repo.GetAll()
.First(fa => fa.ArticleId == articleId);

if(favorite == null) return NotFound();

_repo.Delete(favorite.Id);
_repo.Commit();
return Ok(new { Success = true, Error = (string)null });
}
}

Controllers should be as lean as possible so even the above should be slimmed down even more via an injected service into the controller.

Error handling is a cross-cutting concern and should also be extracted and handled via the framework's extensibility points.

HTTP CODE 405 (Method Not Allowed), When I sent POST data in ASP.NET WebAPI CORS

Check this : Troubleshooting HTTP 405 Errors after Publishing Web API 2 Applications

MVC-Web API: 405 method not allowed


There is problem with the way you are passing data to your method, as you are trying to pass multiple parameter you should try as below

you ajax call need to be like

var client = {
Username:"gx",
Password:"gx"
}
$.ajax(
{
url: "http://domain/api/Clients",
type: "POST",
contentType: "application/json",
data: JSON.stringify(client),
success: function (result) {
alert(result);
}
});

and you web api method will be like this

[HttpPost]
public IHttpActionResult PostClient(Client client)
{
db.Client.Add(client);
db.SaveChanges();
return Ok(client);
}

Also check post here : http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods

MVC-Web API: 405 method not allowed

WebApi probably blocks the CORS request. To enable CORS on WebApi, use the Microsoft.AspNet.WebApi.Cors package. For further details, check http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Web API Put Request generates an Http 405 Method Not Allowed error

So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>.

<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>

Additionally, it is often required to add the following to web.config in the handlers. Thanks to Babak

<handlers>
<remove name="WebDAV" />
...
</handlers>

Getting 405 Method Not Allowed from post request to .Net Core 3.1 API

you have to fix the action route attribute. You can remove [Route("api/pagehit")] attribute, make it default action

 [HttpPost]
public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)

or fix the route attribute

 [HttpPost]
[Route("~/api/addpagehit")]
public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)

in this case you will have to change pagehit to addpagehit in postman too

405 Method Not Allowed for PUT and DELETE in ASP.NET WebAPI

If you are using Visual Studio 2012 or later to develop a Web API application, IIS Express is the default web server. This web server is a scaled-down version of the full IIS functionality that ships in a server product, and this web server contains a few changes that were added for development scenarios. For example, the WebDAV module is often installed on a production web server that is running the full version of IIS, although it may not be in actual use.

The development version of IIS, (IIS Express), installs the WebDAV module, but the entries for the WebDAV module are intentionally commented out, so the WebDAV module is never loaded on IIS Express. As a result, your web application may work correctly on your local computer, but you may encounter HTTP 405 errors when you publish your Web API application to your production web server.

Since your DEV server has full IIS functionality (with WebDAV) it will register multiple handlers for the same verb/method and one of the handlers is blocking the expected handler from processing the request.

So, the WebDAV is overriding your HTTP PUT and DELETE. During the processing of an HTTP PUT request, IIS calls the WebDAV module, When the WebDAV module is called, it checks its configuration and sees it is disabled, so it will return HTTP 405 Method Not Allowed error for any request that resembles a WebDAV request.

You can read more here https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

To disable WebDAV add the following into your web.config

<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>

WebAPI Delete not working - 405 Method Not Allowed

I found the solution eventually!
If you come across the same issue, add the following to your web.config

<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- ADD THIS -->
</modules>
... rest of settings here


Related Topics



Leave a reply



Submit