• webapi之jsonp调用


    定义跨域handle

        public class CorsHandler : DelegatingHandler
        {
            const string Origin = "Origin"; const string AccessControlRequestMethod = "Access-Control-Request-Method"; const string AccessControlRequestHeaders = "Access-Control-Request-Headers"; const string AccessControlAllowOrigin = "Access-Control-Allow-Origin"; const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                bool isCorsRequest = request.Headers.Contains(Origin); bool isPreflightRequest = request.Method == HttpMethod.Options; if (isCorsRequest)
                {
                    if (isPreflightRequest)
                    {
                        return Task.Factory.StartNew<HttpResponseMessage>(() =>
                        {
                            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                            response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault(); if (accessControlRequestMethod != null)
                            {
                                response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                            } string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders)); if (!string.IsNullOrEmpty(requestedHeaders))
                            {
                                response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                            } return response;
                        }, cancellationToken);
                    }
                    else
                    {
                        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
                        {
                            HttpResponseMessage resp = t.Result;
                            resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); return resp;
                        });
                    }
                }
                else
                {
                    return base.SendAsync(request, cancellationToken);
                }
            }
        }

    在Global.asax注册handler

            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
                WebApiConfig.Register(GlobalConfiguration.Configuration);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }

    webapi写法

            public string Get(int id)
            {
                var callback = HttpContext.Current.Request["callback"];
                var u = new User { Name = "AA", Age = id };
                var result = new JavaScriptSerializer().Serialize(u);
                if (string.IsNullOrWhiteSpace(callback))
                    return result;            
                return string.Format("{0}({1})", callback, result);
            }

    前台写法

                    $.ajax({
                        type: "get",
                        url: "http://localhost:21931/api/myapi/12311111",
                        contentType: "application/json;",
                        success: function (msg) {
                            jalert(JSON.stringify(msg));
                        },
                        error: function (a, b, c) {
                            jalert("error");
                        }
                    });

    有追求,才有动力!

    向每一个软件工程师致敬!

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    Apache的Thrift引发的编译思考
    QQ的小秘密
    快速简化Android截屏工作
    Solution of wireless link "PCI unknown" on Centos 7.1
    Java Date Compare
    eclipse集成tomcat日志文件输出配置
    身份证号码验证正则表达式
    curl用法一例 传递代理用户名密码
    HTML 5 placeHolder
    JavaScript(ECMAScript) with 语句
  • 原文地址:https://www.cnblogs.com/wujf/p/5171179.html
Copyright © 2020-2023  润新知