I add cors to my web api application, here's my code:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class CorsPolicyAttribute : System.Attribute, ICorsPolicyProvider { private CorsPolicy _policy; public CorsPolicyAttribute() { _policy = new CorsPolicy { AllowAnyMethod = true, AllowAnyHeader = true }; ////_policy.Origins.Add("http://www.example.com"); var corsOrigins = ConfigHelper.GetAppSettingValue(AttributeConfig.CorsOrigins); if (corsOrigins != null) { if (corsOrigins.Trim() == "*") { _policy.AllowAnyOrigin = true; } else if (string.IsNullOrEmpty(corsOrigins.Trim())) { var origins = corsOrigins.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var origin in origins) { _policy.Origins.Add(origin); } } } } public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return Task.FromResult(_policy); } }
And add this attribute to my controller.
The WebApiConfig.cs
public static void Register(HttpConfiguration config) { config.EnableCors(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
I need to add some authorization data in headers, here's my code by javascript with jquery:
var urls = "http://192.168.0.133/AuthorizationService/api/Auth"; var deviceId = "";$.ajax(urls, { type: 'post', data: { UserName: $("#userName").val(), Password: $("#password").val(), Token: "", DeviceId: deviceId }, headers: { AuthorizationToken: "adac4d7f6d4b78952ddb3b02ccd85434", Authorizationkey: "key" }, success: function(data) {...
The brower will run a preflight option request. here is my preflight request and response.
Request:
OPTIONS http://192.168.0.133/AuthorizationService/api/Auth HTTP/1.1 Host: 192.168.0.133 Connection: keep-alive Access-Control-Request-Method: POST Origin: http://localhost:33202 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36 Access-Control-Request-Headers: accept, authorizationkey, authorizationtoken, content-type Accept: */* Referer: http://localhost:33202/login.html Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8
Response:
HTTP/1.1 200 OK Allow: OPTIONS, TRACE, GET, HEAD, POST Server: Microsoft-IIS/7.5 Public: OPTIONS, TRACE, GET, HEAD, POST X-Powered-By: ASP.NET Date: Mon, 06 Jul 2015 02:43:12 GMT Content-Length: 0
It ends here and doesn't request server to get data.
Do I miss something with web api cors preflight option request?