【问题标题】:AngularJS With Asp.net Web API: $http post returning XMLHttpRequest cannot load: Response for preflight has invalid HTTP status code 405AngularJS 与 Asp.net Web API:$http post 返回 XMLHttpRequest 无法加载:预检响应具有无效的 HTTP 状态代码 405
【发布时间】:2016-10-04 09:47:40
【问题描述】:

当尝试使用 $http 将 json 发布到 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

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

【问题讨论】:

  • 在后端应用 cors
  • 不知道该怎么做。请指导@Rakeschand
  • 这是一个 cors 问题,需要从后端 asp.net 端解决。你可以搜索它。我也不懂asp。

标签: c# asp.net angularjs asp.net-web-api asp.net-web-api2


【解决方案1】:

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

并从网络配置中删除以下内容

   <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 工作一样

但是这些事情让我有些困惑。如果有人能详细说明,我会很高兴

  1. 为什么$.ajax 正常工作而$http 不工作
  2. 我通过cors 做了同样的事情,我在web.config 做了同样的事情,那么为什么cors 有效但web.config 没有?

【讨论】:

  • 我遇到了同样的问题,这为我解决了。我很想知道为什么 web.config 不起作用。
  • 为什么 web.config 没有成功?谁能解释一下。
  • 它也对我有用。感谢@William 的回答。
  • @Vikas OMG 伙计,非常感谢。我一直在尝试使用 web.config 设置解决此问题 4 小时,但它不起作用。非常感谢
  • @Kadaj 欢迎兄弟
【解决方案2】:

我认为您必须在 ajax 调用中设置内容类型:

contentType: 'application/x-www-form-urlencoded; charset=utf-8',

contentType: 'application/json; charset=utf-8',

【讨论】:

    猜你喜欢
    • 2016-09-19
    • 2016-03-27
    • 2017-04-13
    • 2016-08-03
    • 2016-06-30
    • 2016-08-24
    • 2016-10-10
    • 1970-01-01
    • 2016-10-28
    相关资源
    最近更新 更多