Missing method in EnableCorsAttribute - c#

I want to enable CORS from my controller into asp.net core 2 application, so into controller I add attribute like:
[EnableCors(origins: "*", headers: "accept,content-type,origin,x-my-header", methods: "*")]
But I get error on origins:
The best overload for 'EnableCorsAttribute' does not have a parameter
named 'origins'
So I access to EnableCorsAttribute from meta data and I found this methods:
namespace Microsoft.AspNetCore.Cors
{
public class EnableCorsAttribute : Attribute, IEnableCorsAttribute
{
public EnableCorsAttribute(string policyName);
public string PolicyName { get; set; }
}
}
But is supposly it be a method like this:
public EnableCorsAttribute(string origins, string headers, string methods);
Why I don't have it? I need to install something? I'm new in Asp.Net Core and I don't understand why that method isn't in my api. Regards

There's no such attribute like EnableCorsAttribute(string origins, string headers, string methods) in Microsoft.AspNetCore.Cors package.
In Your scenario and based on Enable Cross-Origin Requests (CORS) in ASP.NET Core:
If provided cors configuration is for whole app then in Your ConfigureServices method add cors services:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
and then global cors middleware in Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(builder => builder
.WithOrigins("https://my.web.com", "http://localhost:5001")
.AllowAnyMethod()
.AllowCredentials()
.WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));
//code omitted
}
Replace ("https://my.web.com", "http://localhost:5001") with your origin(s).
In case You would like to have more than one cors configuration then in ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("MyCorsPolicy", builder => builder
.WithOrigins("https://my.web.com", "http://localhost:5001")
.AllowAnyMethod()
.AllowCredentials()
.WithHeaders("Accept", "Content-Type", "Origin", "X-My-Header"));
});
}
in Configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("MyCorsPolicy");
//code omitted
}
and finally in controller:
[EnableCors("MyCorsPolicy")]
public class MyController : Controller
{ ... }

Related

How to make ajax call from .Net Core API in Cross Origin (CORS)? [duplicate]

From what I understand, when enabled CORS accordingly, the response model should include the following header information (provided that I want to allow everything):
Access-Control-Allow-Origin: *
Access-Control-Allow-Method: *
Access-Control-Allow-Header: *
Enabling it in Startup:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddCors();
services.ConfigureCors(options =>
{
options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseCors("AllowAll");
//...
}
The problem is that none of these headers are returned and I get the following error when trying to request from the API:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Make sure you add app.UseCors before app.UseMvc in your Startup.Configure method, because you need the CORS middleware to be applied before the MVC middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
//Add CORS middleware before MVC
app.UseCors("AllowAll");
app.UseMvc(...);
}
Otherwise the request will be finished before the CORS middleware is applied. This is because UseMvc calls UseRouter which ends up adding the RouterMiddleware, and this middleware only executes the next configured middleware when a route handler wasn't found for the request.
In .Net Core Web API 5.0 in Configure method you have to add app.UseCors before other methods, like that:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
...
}
//add CORS
app.UseCors();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

How to enable CORS in Asp.Net Core 3.0 WebAPI

I want to enable CORS with Asp.Net Core 3.0 API project. This is the basic generated Asp.Net Core Api template. Everything is default from the template, except I added CORS settings from the documentation
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(opt =>
{
var origins = Configuration
.GetSection("AllowedHosts")
.Get<string[]>();
opt.AddPolicy("CorsPolicy", builder => builder
.WithOrigins(origins)
.AllowAnyMethod()
.AllowAnyHeader()
.Build());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
What should I set up for getting corret CORS in .net core web api?
Allowed host is :
The order of precedence for Cors should be before adding controllers. It should be added as define in the official documentation: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
Follow this code:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44349")
.AllowAnyMethod()
.AllowAnyHeader();
//.AllowCredentials());
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
As per the official documentation, it must be noted that:
Specifying AllowAnyOrigin and AllowCredentials is an insecure
configuration and can result in cross-site request forgery. The CORS
service returns an invalid CORS response when an app is configured
with both methods.

enabling CORS in .net core webAPI

I've installed NuGet package Microsoft.AspNetCore.Cors 2.2.0
then in my .net core webAPI Startup.cs I have done the following:
public void ConfigureServices(IServiceCollection services) {
......
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options =>
options.WithOrigins("http://localhost:52556")
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMvc();
}
Then when I send post request from my angular app in console I see this error:
Access to XMLHttpRequest at 'http://localhost:52556/api/PaymentDetail'
from origin 'http://localhost:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I thought I've enabled CORS but it seems that something is blocking it. What can be done to solve this problem ?
Try this way. Ithink it's because you are allowing URLs with "http://localhost:52556" only. Using "*" will enable all URLs and if you can want you can limit it to any specific one.
public void ConfigureServices(IServiceCollection services)
{
.........................
services.AddCors(options =>
{
options.AddPolicy("NoRestrictions",
builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());
});;
...............
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppServerSettings> appServerSettings)
{
..........
app.UseCors("NoRestrictions");
..........
}
You are setting Origin for you asp host.
Just replace this line
options.WithOrigins("http://localhost:52556")
with
options.WithOrigins("http://localhost:4200")
I solved same problem in C# by annotations/attributes,
[System.Web.Http.Cors.EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class StudentsController : ApiController{}
in MVC,
use,
// For Action,
[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get(){}
// For Controller,
[Route("api/[controller]")]
[EnableCors("AllowSpecificOrigin")]
public class ValuesController : ControllerBase{}
in your case, replace with this If specific to port number process 4200,
options.WithOrigins("http://localhost:4200");
or you can put No Restrictions,
app.UseCors("NoRestrictions");// To config
// To service
services.AddCors(options =>
{
options.AddPolicy("NoRestrictions",
builder => builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod());
});
Checks whats the origin,
1) checks port number (e.g. 8080 or 8888)
2) domain and sub domain (e.g. google.com or google.net)
3) schema (e.g. http or https)
register origin,
go inside Startup.ConfigureServices and call services.AddCors();
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
enable cors now,
go Startup.Configure and call app.UseCors(builder =>
builder.WithOrigins("http://google.com"));

ASP.NET core Cors policy

I'm having problem setting up Cors policy in my ASP.NET core project.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMemoryCache();
}
I've tried adding app.UseCors("AllowAll"); in Configure(IApplicationBuilder app, IHostingEnvironment env), tried [EnableCors("AllowAll")]before controller declaration:
[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowAll")]
public class TestController : ControllerBase
and before method declaration:
[HttpPost]
[EnableCors("AllowAll")]
public JsonResult Post([FromBody] dynamic request)
and no luck, I'm keep getting "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..."
Maybe someone can help me?
I know this is too late, but can help someone,
using CorsMiddleware in specified order is matters
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
app.UseResponseCaching();
The call to UseCors must be placed after UseRouting, but before
UseAuthorization.
When using Response Caching Middleware, call
UseCors before UseResponseCaching

ASP.NET 5: Access-Control-Allow-Origin in response

From what I understand, when enabled CORS accordingly, the response model should include the following header information (provided that I want to allow everything):
Access-Control-Allow-Origin: *
Access-Control-Allow-Method: *
Access-Control-Allow-Header: *
Enabling it in Startup:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddCors();
services.ConfigureCors(options =>
{
options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.UseCors("AllowAll");
//...
}
The problem is that none of these headers are returned and I get the following error when trying to request from the API:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Make sure you add app.UseCors before app.UseMvc in your Startup.Configure method, because you need the CORS middleware to be applied before the MVC middleware.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
//Add CORS middleware before MVC
app.UseCors("AllowAll");
app.UseMvc(...);
}
Otherwise the request will be finished before the CORS middleware is applied. This is because UseMvc calls UseRouter which ends up adding the RouterMiddleware, and this middleware only executes the next configured middleware when a route handler wasn't found for the request.
In .Net Core Web API 5.0 in Configure method you have to add app.UseCors before other methods, like that:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
...
}
//add CORS
app.UseCors();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

Categories

Resources