AngularJS使用Asp.net Web API:$ http post返回XMLHttpRequest无法加载:预检的响应具有无效的HTTP状态代码405

当尝试使用$http将json POST到Asp.net Web API服务器时,它返回以下错误

 XMLHttpRequest cannot load http://localhost:62158/api/video/add. Response for preflight has invalid HTTP status code 405 

但是从$.ajax发出相同的请求是工作文件。

$ HTTP代码

 $http.post(url, data, config) .success(function (data, status, headers, config) { defered.resolve(data); }) .error(function (data, status, header, config) { defered.reject(data); }); 

$ .ajax代码

 $.ajax({ type: "POST", url: url, data: newVideo, success: function (a) { debugger; }, error: function (e) { debugger; }, dataType: 'json' }); 

asp.net web api代码和配置

web.config中

        

WebApiConfig

 public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); VideoLIbraryDb.Config.setconnection(); var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); } 

API控制器

 [RoutePrefix("api/video")] public class VideoController : ApiController { [Route("add")] [HttpPost] public HttpResponseMessage add([FromBody] db_videos newVideo) { HttpStatusCode statusCode = HttpStatusCode.NotFound; CommonResult result = new CommonResult() /// default { code = ResultCodes.retry.ToString(), message = "Not able to complete request. Retry." }; if (newVideo.video_file_name == null) return Request.CreateResponse(statusCode, result); if (newVideo.video_file_name.Length < 1) return Request.CreateResponse(statusCode, result); if (newVideo.insert()) { statusCode = HttpStatusCode.OK; result.code = ResultCodes.successfull.ToString(); result.message = "Video is added"; } return Request.CreateResponse(statusCode, result); } } 

@Rakeschand你是对的,这是cors的问题

CORS

我使用nu-get命令行在我的项目中安装了Cors

 Install-Package Microsoft.AspNet.WebApi.Cors 

并在App_Start文件夹的WebApiConfig.cs文件中添加了以下代码。

 var enableCorsAttribute = new EnableCorsAttribute("*", "Origin, Content-Type, Accept", "GET, PUT, POST, DELETE, OPTIONS"); config.EnableCors(enableCorsAttribute); 

并从Web配置中删除了以下内容

      

$ http开始工作就像$.ajax工作一样

但这些事让我有些困惑。 如果有人能详细说明,我会很满意

  1. 为什么$.ajax工作, $http无效
  2. 我在web.config做了同样的事情,然后为什么cors工作但web.config没有?

我认为你必须在你的ajax调用上设置内容类型:

 contentType: 'application/x-www-form-urlencoded; charset=utf-8', 

要么

 contentType: 'application/json; charset=utf-8',