AngularJS使用Asp.netWebAPI:$httppost返回XMLHttpRequest无法加载:来自预检的响应具有无效的HTTP状态代码405当尝试使用$http将json发布到Asp.netWebAPI服务器时,它返回以下错误XMLHttpRequest无法加载http://localhost:62158/api/video/add。预检响应具有无效的HTTP状态代码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(数据);});$.ajax代码$.ajax({type:"POST",url:url,data:newVideo,success:function(a){debugger;},error:function(e){debugger;},dataType:'json'});asp.netwebapi代码和配置web.config中config.Routes.MapHttpRoute(name:"DefaultApi",routeTemplate:"api/{controller}/{id}",defaults:new{id=RouteParameter.Optional});VideoLIbraryDb.Config.setconnection();varformatters=GlobalConfiguration.Configuration.Formatters;格式化程序。删除(格式化程序。XmlFormatter);config.Formatters.JsonFormatter.SupportedMediaTypes.Add(newMediaTypeHeaderValue("application/json"));}API控制器[RoutePrefix("api/video")]publicclassVideoController:ApiController{[Route("add")][HttpPost]publicHttpResponseMessageadd([FromBody]db_videosnewVideo){HttpStatusCodestatusCode=HttpStatusCode.NotFound;CommonResultresult=newCommonResult()///default{code=ResultCodes.retry.ToString(),message="无法完成请求。重试。"};如果(newVideo.video_file_name==null)returnRequest.CreateResponse(statusCode,result);如果(newVideo.video_file_name.Length<1)returnRequest.CreateResponse(statusCode,result);如果(newVideo.insert()){statusCode=HttpStatusCode.OK;result.code=ResultCodes.successfull.ToString();result.message="视频已添加";}returnRequest.CreateResponse(statusCode,result);@Rakeschand你是对的,corsCORS有问题我使用nu-get命令行Microsoft.AspNet.WebApi.Cors在我的项目中安装了CorsInstall-Package,并在App_Start文件夹中的WebApiConfig.cs文件中添加了以下代码varenableCorsAttribute=newEnableCorsAttribute("*","Origin,Content-Type,Accept","GET,PUT,POST,DELETE,OPTIONS");配置.EnableCors(enableCorsAttribute);并从网络配置中删除了以下内容$httpstart就像$.ajax一样工作,但这些东西让我有点困惑。如果有人可以详细说明为什么$.ajax有效,$http无效我会很高兴我在web.config中做了同样的事情,那么为什么cors有效但web.config没有?我认为您必须在ajax调用中设置内容类型:contentType:'application/x-www-form-urlencoded;charset=utf-8',或者以上是C#学习教程:AngularJSusingAsp.netWebAPI:$httppostreturnsXMLHttpRequestUnabletoload:preflightresponsehasinvalidHTTPstatuscode405所有内容分享,如果有用给大家,需要了解更多C#学习教程的,希望大家多多关注——contentType:'application/json;charset=utf-8',本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
