zoukankan      html  css  js  c++  java
  • ASP.NET web api 跨域请求

    1.asp.net代码
    (1).增加CorsHandler类,   
    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);
                }
            }
        }
     
    (2).添加配置
            protected void Application_Start()
            {
                GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
         GlobalConfiguration.Configure(WebApiConfig.Register);
            }
    (3).控制器例子
        [RoutePrefix("ajilisiwei")]
        public class ShoppingController : ApiController
        {
            public ShoppingController()
            {
                List<Product> products = new List<Product>() {
                    new Product(){Name="Apple",Price="$20/kg"},
                    new Product(){Name="Banana",Price="$15/kg"},
                    new Product(){Name="Melon",Price="$20/kg"}
                };
                shoppingCart.Name = "MyFruitBaskit";
                shoppingCart.ProductList = products;
            }
     
            [Route("Test")]
            [HttpGet]
            public IEnumerable<Product> GetFruitListByNetJson()
            {
                return shoppingCart.ProductList;
            }
    }
    (4).js 代码
    $.ajax({
    url: "http://localhost:1867/ajilisiwei/Test",
            type: "GET",
    contentType: "application/json;",
    success: function(result) {
                       console.log(result);
                   },
                   error: function (XMLHttpRequest, textStatus, errorThrown) {
                       alert("出错!XMLHttpRequest:" + XMLHttpRequest.status);
                   }
    });
     
    方法二.jsop
    (1).Action代码

            [Route("TestJsonp")]
            [HttpGet]
            public string GetFruitListByJsonp()
            {
                    return new JavaScriptSerializer().Serialize(shoppingCart.ProductList);
            }

    (2).js代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/jquery.min.js"></script>
    </head>
    <body>
    <script>
    $.getJSON("http://localhost:1867/ajilisiwei/TestJsonp?jsonpcallback=test", //"test" 这里除了写问号,随便写啥都可以,好奇怪
    function(json) {
    console.log(json);
    }
    );
    </script>
    </body>
    </html>


    
    
    说明: 还有这种方法。
       $.ajax({
            type: "get",
            url: "http://localhost:1867/ajilisiwei/TestJsonp",
            //dataType: "jsonp",
            jsonp: "jsonpcallback",
            data: "jsonpcallback=?",
            success: function (json) {
                console.log(json);
            }
        });
    验证了好久, 不用增加 dataType:"jsonp" 设置。url内容如下:http://localhost:1867/ajilisiwei/TestJsonp?jsonpcallback=?   这是在asp.net  web api下验证的
     
  • 相关阅读:
    Treap 树堆 容易实现的平衡树
    (转)Maven实战(二)构建简单Maven项目
    (转)Maven实战(一)安装与配置
    根据请求头跳转判断Android&iOS
    (转)苹果消息推送服务器 php 证书生成
    (转)How to renew your Apple Push Notification Push SSL Certificate
    (转)How to build an Apple Push Notification provider server (tutorial)
    (转)pem, cer, p12 and the pains of iOS Push Notifications encryption
    (转)Apple Push Notification Services in iOS 6 Tutorial: Part 2/2
    (转)Apple Push Notification Services in iOS 6 Tutorial: Part 1/2
  • 原文地址:https://www.cnblogs.com/ajilisiwei/p/6231492.html
Copyright © 2011-2022 走看看