AngularJS使用Asp.net Web API:$ http post返回XMLHttpRequest无法加载:预检的响应具有无效的HTTP状态代码405
当尝试使用$http
将json POST到Asp.net Web API服务器时,它返回以下错误
XMLHttpRequest cannot load https://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',
要么
上述就是C#学习教程:AngularJS使用Asp.net Web API:$ http post返回XMLHttpRequest无法加载:预检的响应具有无效的HTTP状态代码405分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
contentType: 'application/json; charset=utf-8',
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1039101.html