I want to build an ASP.NET Service thats called from another server but it does not allow me to access the Service.
-
What did you try so far? – Dieter Meemken Jan 31 '17 at 08:12
-
Possible duplicate of [How to enable CORS in ASP.NET Core](https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core) – Michael Freidgeim May 02 '18 at 21:15
4 Answers
All you need is to insert this code in your startup.cs:
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
just keep in mind to use it above:
app.UseMvc()
Have fun!

- 1,339
- 1
- 12
- 32
You should take a look at this article to see all the available options:
simple setup
public void ConfigureServices(IServiceCollection services) { services.AddCors(); }
setup with middleware
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Shows UseCors with CorsPolicyBuilder. app.UseCors(options => options.WithOrigins("http://example.com").AllowAnyMethod()); // other code may come here }
CORS in MVC project
Action level
[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{
[EnableCors("AllowSpecificOrigin")]
public IActionResult Index()
{
return View();
}
}
Controller level
[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{
}
and much options like allowed origins, allowed HTTP methods, exposed response headers, how to handle credentials.
Try setting up yourself and come here with a specific problem if you encounter one.

- 1,551
- 12
- 32
- 52

- 22,016
- 16
- 145
- 164
Please make sure to install the nuget package
Install-Package Microsoft.AspNetCore.Cors
Configure the startup.cs
similar to the following:
public class Startup
{
public Startup(IHostingEnvironment env)
{
//...
}
public void ConfigureServices(IServiceCollection services)
{
//...
//Register Cors policy
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMvc();
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseCors("CorsPolicy"); //Make sure the policy name matches with the provided above
//...
}
}

- 2,448
- 3
- 20
- 33
You can configure CORS in Startup class in the ConfigureServices method `
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
apply it to every request
public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");
}
you can apply on Controller or Method Also e.g add attribute
[EnableCors("MyPolicy")]

- 2,755
- 17
- 32