405 Method Not Allowed Web API

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

Web API Post error - HTTP Error 405.0 - Method Not Allowed

This was happening because of the default routing convention was not being followed initially but after your corrected your base url, then the API started working. According to the specs:

In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives a request, it routes the request to an action.

To determine which action to invoke, the framework uses a routing table. The Visual Studio project template for Web API creates a default route:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Hence when you need to call your API, your base url should have the /api to it.

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.

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>

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>

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

Blazor and WebApi in same solution: Why is the POST response 405: Method not allowed?

I have to configure CORS in tzh WebApi project. Now it works.

Insert this code in the public void Configure() in the Startup.cs

app.UseCors(cors => cors
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials()
);

405 method options not allowed in asp.net web api controller?

In your handlers after <remove name="OPTIONSVerbHandler"/>, add this:

<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
modules="IsapiModule" requireAccess="None"
scriptProcessor="C:\Windows\System32\inetsrv\asp.dll"
resourceType="Unspecified" />

See the answer at IIS hijacks CORS Preflight OPTIONS request.

Or maybe even just this:

 <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS"
modules="ProtocolSupportModule" requireAccess="None" />

If that doesn’t work, something that will is adding the following in your global.asax or other code:

protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}


Related Topics



Leave a reply



Submit