The 405 Method Not Allowed error occurs when the web server is configured in a way that does not allow you to perform a specific action for a particular URL. It's an HTTP response status code that indicates that the request method is known by the server but is not supported by the target resource. Support.
However, in general, following HTTP standards, a 405 response status code means “Method Not Allowed”. So literally, a POST method is not allowed for that url endpoint on the server, in question. The server explicitly denies a POST method to that endpoint.
Via nuget make the installation of the CORS web API package for your project:
Install-Package Microsoft.AspNet.WebApi.Cors
In WebApiConfig add the following lines:
var cors = new EnableCorsAttribute ("*", "*", "*");
config.EnableCors (cors);
Ensure that you have OPTIONS as one of the allowed verb in your web.config and that it's being handled by the default handler.
<system.web>
...
<httpHandlers>
...
<add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>
This one solved my problem
Step 1
Install the Cors package Microsoft.AspNet.WebApi.Cors (Right Click Solution > Manage Nuget Package > And Then Search for Cors)
Step 2
put this line in the WebApiConfig.cs file
public static void Register(HttpConfiguration config)
{
config.EnableCors(new EnableCorsAttribute("http://localhost:3000", headers: "*", methods: "*"));
.
.
.
}
Change http://localhost:3000 to the address of the API Caller
In the end I have solved this by changing the ajax request. I found out that the OPTIONS
preflight is only sent in certain situations - one of them being if the request contains a Content-Type
that is not one of the following types:
So by removing the content-type in my ajax request and changing it to the following:
$.ajax({
type: "POST",
crossDomain: true,
data: student,
dataType: 'json',
url: 'http://www.example.com/api/save',
success: function (result) {
console.log(result);
}
});
I was able to get it working.
This page has useful information about simple requests and how to avoid preflight requests
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With