zoukankan      html  css  js  c++  java
  • Web Api 跨域问题

    1.如果是4.0 需要自己实现这个功能

     public class CorsHandler : System.Net.Http.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 System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                bool isCorsRequest = request.Headers.Contains(Origin);
                bool isPreflightRequest = request.Method == System.Net.Http.HttpMethod.Options;
    
                if (isCorsRequest)
                {
                    if (isPreflightRequest)
                    {
    
    
                        return System.Threading.Tasks.Task.Factory.StartNew<System.Net.Http.HttpResponseMessage>(() =>
                        {
                            System.Net.Http.HttpResponseMessage response = new System.Net.Http.HttpResponseMessage();
                            response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                            response.StatusCode = System.Net.HttpStatusCode.OK;
    
                            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<System.Net.Http.HttpResponseMessage>(t =>
                        {
                            System.Net.Http.HttpResponseMessage resp = t.Result;
                            resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); return resp;
                        });
                    }
                }
                else
                {
                    return base.SendAsync(request, cancellationToken);
                }
            }
        }

    Global.asax 文件进行注册

     GlobalConfiguration.Configuration.MessageHandlers.Add(new MobileAPI.Controllers.CorsHandler());

    2.如果是4.5那就可以用 CORS 

        在WebApiConfig 配置    config.EnableCors();

        在action 可以这么用

       

     [EnableCors(origins: "*", headers: "*", methods: "*")]
            public async System.Threading.Tasks.Task<HttpResponseMessage> GetWeathByCity(string cityId)
            {
              
                string uri = "http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101010100";
                HttpClient client = new HttpClient();
                var body = await client.GetStringAsync(uri);
               
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(body, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }

    3.自己实现请求限制  

    示例:[MyCorsPolicy]

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
            public class MyCorsPolicyAttribute : Attribute, ICorsPolicyProvider
            {
                private CorsPolicy _policy;
    
                public MyCorsPolicyAttribute()
                {
                    // Create a CORS policy.
                    _policy = new CorsPolicy
                    {
                        AllowAnyMethod = true,
                        AllowAnyHeader = true
                    };
    
                    // Add allowed origins.
                    _policy.Origins.Add("********");
                    _policy.Origins.Add("*******");
                }
    
                public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)
                {
                    return Task.FromResult(_policy);
                }
            }

    或者这样

     public class CorsPolicyFactory : ICorsPolicyProviderFactory
            {
                ICorsPolicyProvider _provider = new MyCorsPolicyProvider();
                public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
                {
                    return _provider;
                }
            }
    WebApiConfig 注册
    config.SetCorsPolicyProviderFactory(new CorsPolicyFactory());
    config.EnableCors();
  • 相关阅读:
    回车代码兼容火狐浏览器
    js区分浏览器类型
    阶段总结(2014-07-23)
    Spring学习笔记 2014-7-9
    Maven学习笔记
    QQ协议的研究
    模仿微信打飞机做的程序
    滚动字幕
    13年8月15日阿里云服务器网络故障事件
    [转]程序员自己写的神器 MonoDevelop 4 (Xamarin Studio) Debugging for Unity
  • 原文地址:https://www.cnblogs.com/linsu/p/6026681.html
Copyright © 2011-2022 走看看