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();