Reputation: 1403
I have designed a MVC 4.5 Web API in .Net. HTTP request has to be made from Jquery AJAX Call. After making the call(POST) I get the following error in console. Can anyone help me to identify what I am doing wrong?
OPTIONS http://192.168.xx.xx:1245/api/values 405 (Method Not Allowed) jquery-1.7.1.min.js:4
OPTIONS http://192.168.xx.xx:1245/api/values Invalid HTTP status code 405 jquery-1.7.1.min.js:4
XMLHttpRequest cannot load http://192.168.xx.xx:1245/api/values. Invalid HTTP status code 405
Upvotes: 0
Views: 1805
Reputation: 201
I spent a whole day fixing this issue in my API.
Here is what i did to overwrite the OPTION method in the API
You have to set this in your web.cnofig inside system.webservers
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Accept, Authorization, Data, Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
</customHeaders>
</httpProtocol>
Then in your WebApiConfig.cs put this code
public class OptionsHttpMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Options)
{
return Task.Factory.StartNew(() =>
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
return resp;
});
}
return base.SendAsync(request, cancellationToken);
}
}
And register that with this line in the Register function in the same WebApiConfig.cs
GlobalConfiguration.Configuration.MessageHandlers.Add(new OptionsHttpMessageHandler());
Upvotes: 1
Reputation: 1039398
You are violating the same origin policy restriction
by making a cross domain AJAX call which is not allowed by default. You might need to enable CORS on the Web API side: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Install-Package Microsoft.AspNet.WebApi.Cors -project YourWebApiProject
and then in your config simply enable CORS:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This will enable you to make cross domain AJAX requests to your Web API from browsers that support CORS.
Upvotes: 2