Workaround One:
Public classCroshandler:delegatinghandler {Private Const stringOrigin ="Origin"; Private Const stringAccesscontrolrequestmethod ="Access-control-request-method"; Private Const stringAccesscontrolrequestheaders ="access-control-request-headers"; Private Const stringAccesscontrolalloworign ="Access-control-allow-origin"; Private Const stringAccesscontrolallowmethods ="Access-control-allow-methods"; Private Const stringAccesscontrolallowheaders ="access-control-allow-headers"; Private Const stringAccesscontrolallowcredentials ="access-control-allow-credentials"; /// <summary> ///asynchronously sends an HTTP request to an internal handler to be sent to the server/// </summary> /// <param name= "Request" ></param> /// <param name= "CancellationToken" ></param> /// <returns></returns> protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) {BOOLIscrosrequest =request. Headers.contains (Origin); //whether to pre-request BOOLIsprefilightrequest = Request. Method = =httpmethod.options; if(iscrosrequest) {Task<HttpResponseMessage> Taskresult =NULL; if(isprefilightrequest) {Taskresult= Task.factory.startnew{httpresponsemessage response=Newhttpresponsemessage (httpstatuscode.accepted); Response. Headers.add (accesscontrolalloworign, request.) Headers.getvalues (Origin). FirstOrDefault ()); stringMETHOD =request. Headers.getvalues (Accesscontrolrequestmethod). FirstOrDefault (); if(!string. IsNullOrEmpty (method)) {response. Headers.add (Accesscontrolallowmethods, method); } stringheaders =string. Join (", ", request. Headers.getvalues (accesscontrolrequestheaders)); if(!string. IsNullOrEmpty (Headers)) {response. Headers.add (Accesscontrolallowheaders, Headers); } response. Headers.add (Accesscontrolallowcredentials,"true"); returnresponse; }, CancellationToken); } Else{Taskresult=Base. SendAsync (Request, CancellationToken). Continuewith { varResponse =T.result; Response. Headers.add (accesscontrolalloworign, request.) Headers.getvalues (Origin). FirstOrDefault ()); Response. Headers.add (Accesscontrolallowcredentials,"true"); returnresponse; }, CancellationToken); } returnTaskresult; } return Base. SendAsync (Request, CancellationToken); } }
Call:
How to call: Add GlobalConfiguration.Configuration.MessageHandlers.Add in the Application_Start method of the Global.asax file (new Croshandler ( ), or add the following WebApiConfig.cs: Config.MessageHandlers.Add (New Croshandler ());
Workaround Two:
Add the code between the <system.webServer> nodes under Web. config:
"Access-control-allow-origin"Value="*"/> <add name="access-control-allow-headers"Value="Access-control-allow-origin, AppKey, Authorization"/> <add name="Access-control-allow-methods"Value="GET, POST, OPTIONS"/> <add name="Access-control-request-methods"Value="GET, POST, OPTIONS"/> </customHeaders> C#api Resolving cross-domain issues under custom request headers