Reputation: 1562
I have an ASP.Net Core and a Web Api Project in the same solution. I'm calling Get, Post, Put, Delete from my Core Project which is defined in my Api project. Definitely I need to enable CORS.
Bellow is the code that I added in my Web Api web.config file,
<httpProtocol>
<customHeaders>
<!-- Enable Cross Domain AJAX calls -->
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
And my Ajax code from Core project,
$.ajax({
"url": "myApiUrl",
"type": "Get",
"data": {
//Here I'm passing a value
},
success: function (d) {
}
I set both the projects as startup project. Not an issue. It's calling the Api method and returning the data. But some times it's not returning anything, even the method returns data, I'm getting the error in browser console
that I mentioned in my question title. I checked many answers in SO, including this one, all said that I need to add access control
in my response header
. Any one tell me where I need to add exactly and what I need to add so that it will work as expected.
I checked with Asp.net MVC project too instead Core, same thing happened.
Note: I added CORS in my Web Api Project not in my Web Project.
Upvotes: 2
Views: 1382
Reputation: 5284
Try this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CrossPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ...
}
For every request:
public void Configure(IApplicationBuilder app)
{
app.UseCors("CrossPolicy");
// ...
}
OR
[EnableCors("CrossPolicy")]
You can find more information in this and this link.
Hopefully it's help for you.
Upvotes: 1
Reputation: 493
I guess you have not correctly enabled CORS in Web API. You can do this by following process:
1) You can put [EnableCors] Attribute at the controller in Web API or globally in WebAPI Config.
Example -
[EnableCors("*", "*", "*")]
.
Put this on the controller (for which you want to allow CORS).
Note: You can modify attributes to this filter to allow certain methods, URLs etc
2) Call enableCors in WebAPi.config i.e.
public static void Register(HttpConfiguration config)
{
// Other configuration omitted
config.EnableCors();
}
EDIT: If you need to Enable CORS globally, delete EnableCors attribute from controller and modify EnableCors() line in WebApiConfig.cs file to be :
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
Upvotes: 1