AngularJS随着Asp.net的Web API:$ HTTP POST返回XMLHtt prequest无法加载:为preflight响应具有无效的HTTP状态code 405 [英] AngularJS With Asp.net Web API: $http post returning XMLHttpRequest cannot load: Response for preflight has invalid HTTP status code 405

查看:3922
本文介绍了AngularJS随着Asp.net的Web API:$ HTTP POST返回XMLHtt prequest无法加载:为preflight响应具有无效的HTTP状态code 405的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用为POST JSON来Asp.net的Web API服务器的$ HTTP返回其下面的错误


  

XMLHtt prequest无法加载的http://本地主机:62158 / API /视频/添加
  为preflight响应具有无效的HTTP状态code 405


但实现从 $。阿贾克斯同一请求工作的文件。

$ HTTP code

  $ http.post(网址,数据,配置)
    .success(功能(数据,状态,头,配置){
        defered.resolve(数据);
    })
    .error(功能(数据,状态,头,配置){
        defered.reject(数据);
    });

$。阿贾克斯code

  $阿贾克斯({类型:POST,
                网址:网址,
                数据:newVideo,
                成功:函数(){
                    调试器;                },
                错误:功能(E){
                    调试器;                },
                数据类型:JSON
            });

asp.net网页API code和配置

的web.config

 < httpProtocol>
    < customHeaders>
        <添加名称=访问控制允许来源VALUE =*/>
        <添加名称=访问控制 - 允许 - 头VALUE =Content-Type的/>
        <添加名称=访问控制允许的方法VALUE =GET,POST,PUT,DELETE,OPTIONS/>
    < / customHeaders>
< / httpProtocol>

WebApiConfig

 公共静态无效的注册(HttpConfiguration配置)
{
    //网页API的配置和服务    //网页API路线
    config.MapHttpAttributeRoutes();    config.Routes.MapHttpRoute(
        名称:DefaultApi
        routeTemplate:API / {}控制器/(编号),
        默认:新{ID = RouteParameter.Optional}
    );
    VideoLIbraryDb.Config.setconnection();    VAR格式化= GlobalConfiguration.Configuration.Formatters;    formatters.Remove(formatters.XmlFormatter);    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(新MediaTypeHeaderValue(应用/ JSON));
}

API控制器

  [路线preFIX(API /视频)]
    公共类的视频控制器:ApiController
    {
        [路线(加)]
        [HttpPost]
        公众的Htt presponseMessage添加([FromBody] db_videos newVideo)
        {
            的HTTPStatus code状态code =的HTTPStatus code.NotFound;            CommonResult结果=新CommonResult()///默认
            {
                code =结果codes.retry.ToString()
                消息=无法完成请求。重试。
            };            如果(newVideo.video_file_name == NULL)
                返回Request.CreateResponse(状态code,导致);            如果(newVideo.video_file_name.Length&。1)
                返回Request.CreateResponse(状态code,导致);
            如果(newVideo.insert())
            {
                状态code =的HTTPStatus code.OK;
                。结果code =结果codes.successfull.ToString();
                result.message =视频添加;
            }            返回Request.CreateResponse(状态code,导致);
        }
    }


解决方案

@Rake​​schand 你是对的,这是问题的 CORS

一个Cors

我用NU-get命令行中我的项目中安装一个Cors

 安装封装Microsoft.AspNet.WebApi.Cors

和加入WebApiConfig.cs的follwoing code从App_Start文件夹中。

  VAR enableCorsAttribute =新EnableCorsAttribute(*,
                                               起源,内容类型,接受
                                               GET,PUT,POST,DELETE,OPTIONS);

和移除web配置以下

 <删除名称=X供电,通过/>
                    <添加名称=访问控制允许来源VALUE =*/>
                    <添加名称=访问控制 - 允许 - 头VALUE =接受,内容类型,起源/>
                    <添加名称=访问控制允许的方法VALUE =GET,PUT,POST,DELETE,OPTIONS/>

$ HTTP开始工作,就像 $。阿贾克斯正在

但这些东西给我留下了一些混乱。我将是巨大的充满如果有人能细说


  1. 为什么 $。阿贾克斯正在和 $ HTTP 不能正常工作

  2. 我用 CORS做同样的事情的我在做的web.config 那么,为什么 CORS 工作,但的web.config 没?

When trying to POST json to Asp.net web api server using $http its returning the following error

XMLHttpRequest cannot load http://localhost:62158/api/video/add. Response for preflight has invalid HTTP status code 405

but making the same request from $.ajax is working file.

$HTTP Code

$http.post(url, data, config)
    .success(function (data, status, headers, config) {
        defered.resolve(data);
    })
    .error(function (data, status, header, config) {
        defered.reject(data);
    });

$.ajax Code

           $.ajax({ type: "POST",
                url: url,
                data: newVideo,
                success: function (a) {
                    debugger;

                },
                error: function (e) {
                    debugger;

                },
                dataType: 'json'
            });

asp.net web api code and configuration

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 controller

[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 you were right and it was the issue of cors

Cors

I installed Cors in my project using nu-get command line

Install-Package Microsoft.AspNet.WebApi.Cors

and added the follwoing code in WebApiConfig.cs file from App_Start folder.

var enableCorsAttribute = new EnableCorsAttribute("*",
                                               "Origin, Content-Type, Accept",
                                               "GET, PUT, POST, DELETE, OPTIONS");

and removed the following from the web config

   <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 started working just like the $.ajax was working

but these things left me with some confusion. I would be great full if anyone can elaborate

  1. why the $.ajax was working and $http was not working
  2. I did the same thing by cors the I had done in web.config then why did cors worked but web.config didn't?

这篇关于AngularJS随着Asp.net的Web API:$ HTTP POST返回XMLHtt prequest无法加载:为preflight响应具有无效的HTTP状态code 405的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆