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
工作一样
但这些事让我有些困惑。 如果有人能详细说明,我会很满意
- 为什么
$.ajax
工作,$http
无效 - 我在
web.config
做了同样的事情,然后为什么cors
工作但web.config
没有?
我认为你必须在你的ajax调用上设置内容类型:
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
要么
contentType: 'application/json; charset=utf-8',
- 将Angular的请求压缩到Web API
- ngcsv – 在safari和IE浏览器中遇到麻烦
- Angular $ http错误响应statusText始终未定义
- entity framework在db.SaveChanges()期间创建新数据行
- 从服务中的JavaScript HTML调用WCF服务
- AngularJs脚本在部署后不起作用,它会出错
- Angular路由模板URL是否支持ASP.Net MVC 5项目中的* .cshtml文件?
- 凭据标志为“true”,但是“Access-Control-Allow-Credentials”
- AngularJs和ASP.NET MVC 5-ng-model覆盖文本框值