码迷,mamicode.com
首页 > Windows程序 > 详细

ASP.NET Web API 跨域访问

时间:2015-04-27 21:42:27      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:


情景:http://localhost:8080/的web应用下访问http://localhost:8081下的Action时称为跨域访问。

        前提,启动8080web应用实例,再启动8081web应用实例利用ajax去访问。 

 

首先,在自己的Web API应用中,添加NuGet服务包,联机:

 技术分享

 然后选择图中的,安装:

 技术分享

 

 在Web API应用的App_Start/WebApiConfig.cs下的

        public static void Register(HttpConfiguration config)
        {}

下最后添加一句代码: 

config.EnableCors(new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true, PreflightMaxAge = 600 });

 

然后在8080下的cshtml 或html页面利用ajax访问:

 

 

     <script type="text/javascript">
         $(function () {

            Index_Get();
        });
        
        Index_Get = function () {
            $.ajax({
                url: "http://localhost:1687/Api/Console/Index_Get",
                type: "post",
                data: JSON.stringify({}),
                //dataType: "json",//表示返回值类型,不必须
                contentType: "application/json;charset=utf-8",//必须有,请求类型
                success: function (o) {
                    alert(o);
                },
                error: function (o) {
                    alert("您好,您做错了");
                },
                processData: false
            });
        }
    </script>

 processData默认值: true。默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

 


 

  $.ajax({

            url:url,
            data:JSON.stringify(data),
            success: function (data, textStatus, jqXHR) {
                if (typeof (success) == "function") {
                    success(data, textStatus, jqXHR)
                }
            },
            error:function(jqXHR, textStatus,errorThrown ){
                if(typeof(error)=="function"){
                    error(jqXHR,textStatus,errorThrown);
                }
            },
            xhrFields: {
                withCredentials: true
            },
            headers: {
                "Authorization": "PlatformAuth " + App.Setting.AuthToken,
            },
            contentType: "application/json",//请求类型为json格式
            cache: "false",
            type: "POST",
            processData: false,//是否将ajax中的JSON.stringify({})转换为?a=f&b=g形式
        }) 

 

ASP.NET Web API 跨域访问

标签:

原文地址:http://www.cnblogs.com/whaozl/p/4461399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!