• 使用Cors在WebApi中实现跨域请求,请求方式为angular的 $http.jsonp


     

    使用Cors在WebApi中实现跨域请求

    第一步,在webapi项目中安装cors

     

     

     在Web API配置文件中(Global.asax)进行全局配置:

     public class WebApiApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                #region 跨域请求
                var config = GlobalConfiguration.Configuration;
                var cors = new EnableCorsAttribute("*", "*", "*");
                config.EnableCors(cors);
                #endregion
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
            }
        }

     第二部,代码编写

    控制器头部代码

     [EnableCors(origins: "*", headers: "*", methods: "*")]
        public class MinderController : ApiController
        {
    
    
    
    }

    返回数据源代码,请注意,这里一定不要返回为字符串。如果返回为字符串,那么JSONP的方法不会识别出来,将永远不会去调用Success方法,我使用的是

    angular中$http请求JSONP的,结果返回的数据状态码为200,但是一直没有执行success方法。调试了一天没有结果,后来返回的内容直接输出就可以了。
     
    代码1:
     public HttpResponseMessage GetMindData(int? CompanyID, int? parent, string callback)
            {
               
                Object root = new Object();
                
    
                return new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(callback + "(" + JsonConvert.SerializeObject(root) + ")", System.Text.Encoding.UTF8, "text/plain")
                };
            }

    代码2:改短代码是使用MVC的方式返回的JSONP数据:

      public JavaScriptResult GetMindData(int? CompanyID, string callback)
            {
     
                Object root = new Object ();
                root.root = company;
                string js = callback + "(" + JsonConvert.SerializeObject(root) + ")";
     
                return JavaScript(js);
            }

    前端的调用:

    angular中$http请求JSONP

     angular.module('kityminderDemo', ['kityminderEditor'])
            .controller('MainController', function ($scope, $http, $sce) {
           
                $scope.initEditor = function (editor, minder) {
                    window.editor = editor;
                    window.minder = minder;
                    /*
                                   $http.get("e.html").then(function (data) {  //查询Use里的所有数据                    
                                       window.editor.minder.importData('json', JSON.stringify(data.data));
                                   });                
                   */
                
                    var myUrl = "https://XXX?callback=JSON_CALLBACK";
                     
                    $sce.trustAsResourceUrl(myUrl);
                    $http.jsonp(myUrl)
                        .success(function (response) {
                            var a = 0;
                            console.log(response);
                            window.editor.minder.importData('json', JSON.stringify(response));
                        }).error(function (e) {
                            console.log(e);
                        });
    
                };
            });
    

    JS的JSONP请求方式:未经验证谨慎使用

    $.ajax({
                url: RESTurl,
                type: 'GET',
                dataType: 'jsonp',
                jsonp: 'callback',
                jsonpCallback: 'myCallback'
            });
    
            window.myCallback = function (data) {
                console.log(data);
            };
  • 相关阅读:
    豆瓣书籍数据采集
    动画精灵与碰撞检测
    图形
    模块
    对象
    函数
    列表与字典
    python 感悟
    SqlServer自动备份数据库(没有sql代理服务的情况下)
    关于AD获取成员隶属于哪些组InvokeGet("memberOf")的问题
  • 原文地址:https://www.cnblogs.com/vincentvoid/p/10649393.html
Copyright © 2020-2023  润新知