尝试使用JSON将JSON发布到Asp.net Web API服务器时$http,返回以下错误
$http
XMLHttpRequest cannot load http://localhost:62158/api/video/add. Response for preflight has invalid HTTP status code 405
但是从$.ajax工作文件发出相同的请求。
$.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
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol>
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 的问题 *
科尔斯
我使用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);
并从网络配置中删除了以下内容
<remove name="X-Powered-By" /> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" /> <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
$ http开始工作,就像$.ajax工作一样
但是这些事情使我有些困惑。 如果有人可以详细说明,我将非常满意
cors