Reputation: 42390
I'm trying to get a json response from a WepApi2 controller
[EnableCors(origin = "*", methods = "*", headers = "*")]
public class DataController {
public IEnumerable<int> GetData(RequestItems items) {
...
}
}
Using this to try get the data...
$.ajax({
type: "POST",
method: "POST",
contentType: "application/json",
url: "https://api.mysite.com/api/Data/GetData",
data: JSON.stringify({ /* some data here */ }),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*"
},
xhrFields: {
withCredentials: true
},
success: function(xhr) {
console.log(xhr);
},
error: function(e) {
console.log(e);
}
});
And I'm getting this...
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mysite.com/api/Data/GetData. (Reason: CORS header 'Access-Control-Allow-Origin' does not match '*')
I've trawled through virtually everything I can find about CORS and jQuery on the web, and I just have no idea what to do. PLEASE HELP!
Upvotes: 1
Views: 4644
Reputation: 181
You can follow this steps -
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<httpProtocol>
<!-- THESE HEADERS ARE IMPORTANT TO WORK WITH CORS -->
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
2.API Global.asax add this-
protected void Application_BeginRequest(object sender, EventArgs e)
{
//this is required to work with CORS request
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
3.In JS file call this way -
function LoadReport() {
var data = {};
var URL = APIBaseUrl + '/api/statements/get_user_statements?instance_id=1';
$.support.cors = true;
$.ajax({
contentType: false,
processData: false,
beforeSend: function (req) {
req.setRequestHeader('Authorization', 'Bearer ' + access_token);
},
crossDomain: true,
url: URL,
type: 'GET',
success: function (response) {
alert('yes');
},
error: function (xhr, textStatus, errorThrown) {
alert('try again');
}
});
}
Upvotes: 0
Reputation: 7498
I'm using CORS with WebAPI without issues. Perhaps I'll just describe what I do. If it won't be relevant I'll remove answer. This works for me though.
Edit: Also note, that with CORS the headers have to come in response.
I'm of course using the OWIN
. My Startup.cs
looks like:
public static void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
WebApiConfig.Register(config);
app.UseWebApi(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
Notice, that I had to explicitly EnableCors
on my WebApiConfig
. Then of course continue by app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Then just enable cors on my ApiController
class as you do:
[EnableCors("*", "*", "GET,POST")]
public class FauxDBController : ApiController
{
[HttpPost]
[AllowAnonymous]
public mJSONSQLFAUXResponse XYZ(mJSONSQLFAUX data)
{
}
}
Just to show what NuGet packages I use, here is my packages.config
:
<packages>
<package id="Microsoft.AspNet.Cors" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Cors" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Cors" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />
<package id="Owin" version="1.0" targetFramework="net452" />
</packages>
Finally, I don't use jQuery
but my angular.js
file with ajax routine looks like:
$http.post('http://localhost:59113/api/FauxDB/XYZ', { }).success(function (data, status, headers, config) {
// something..
}).error(function (data, status, headers, config) {
// something..
});
Hope it helps.
Upvotes: 4