MVC 4.5 Web API请求不起作用

我在.Net中设计了一个MVC 4.5 Web API。 HTTP请求必须来自Jquery AJAX Call。 在进行调用(POST)后,我在控制台中收到以下错误。 任何人都可以帮我确定我做错了什么吗?

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 

您通过进行跨域AJAX调用违反了same origin policy restriction ,默认情况下不允许这样做。 您可能需要在Web API端启用CORS: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

 Install-Package Microsoft.AspNet.WebApi.Cors -project YourWebApiProject 

然后在你的配置中只需启用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 } ); } } 

这将使您能够从支持CORS的浏览器向Web API发出跨域AJAX请求。

我花了一整天时间在我的API中解决这个问题。

这是我在API中覆盖OPTION方法所做的

你必须在system.webservers里面的web.cnofig中设置它

        

然后在你的WebApiConfig.cs中输入这段代码

 public class OptionsHttpMessageHandler : DelegatingHandler { protected override Task 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); } } 

并在同一个WebApiConfig.cs中的Register函数中注册该行

 GlobalConfiguration.Configuration.MessageHandlers.Add(new OptionsHttpMessageHandler());