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

Vik*_*sal 11 c# asp.net asp.net-web-api angularjs asp.net-web-api2

当尝试使用$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
Run Code Online (Sandbox Code Playgroud)

但是从$.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);
    });
Run Code Online (Sandbox Code Playgroud)

$ .ajax代码

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

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>
Run Code Online (Sandbox Code Playgroud)

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"));


}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Vik*_*sal 20

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

CORS

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

Install-Package Microsoft.AspNet.WebApi.Cors
Run Code Online (Sandbox Code Playgroud)

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

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

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

   <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" />
Run Code Online (Sandbox Code Playgroud)

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

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

  1. 为什么$.ajax工作而且$http没有工作
  2. 我做了同样的事情cors,web.config那时为什么cors工作但web.config没有?