CORS error working only for one controller - c#

I am working on a dotnet core web api.
My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)
I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:
Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.
It works the for the first request but not for the second request (giving the same error)
This is what I have used for Enabling CORS
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
;
});
}
How can I make it work for both the requests.

I encountered your problem. For solve this firstly add this code to startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
.AllowCredentials();
}));
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
});
}}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DiagnosticListener diagnosticListenerSource, DiagnosticObserver diagnosticObserver)
{
app.UseCors("MyPolicy");
}
Then "Access-Control-Allow-Origin" should be added to the api send request header.
Typescript example:
fetch(window.appSettings.API_URL + path, {
redirect: 'follow',
method,
body: data === null ? null : JSON.stringify(data),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
Authorization: 'Bearer ' + bToken,
},
});
You can change origin if you want for security

Try this code to see if it work for you
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(
options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
);
app.UseMvc();
}

You can use below code in ConfigureServices method
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
and in Configure method use
app.UseCors("CorsPolicy");

Related

cors c# web API react

(My English is not good)
Hello so I am having problem where when I have my web API on my server and then try to use my react website from my main pc I get Cors error. when I run both my webAPI and my react on my main pc it owrks but need it to work from the server coz we are several ppl wokring on it.
I would love it someone could help me out.
Error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ServerIP/api/user. (Reason: CORS request did not succeed).
I have tried some different things like adding:
public static void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
and then when that didn't work I tried fixing the end point
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}"
);
endpoints.MapControllers();
});
Also tried adding this infront of our two controller classes
[EnableCors("*", "*", "*")]
This is how the React looks like:
import Axios from 'axios'
const WorkifyAPI = Axios.create({
baseURL: 'https://ServerIP:42069/api'
})
export default WorkifyAPI
the react service:
import http from '../WorkifyAPI'
const GetallWorkouts = (userID: string) => {
return http.get(`/user/${userID}/WorkoutData`)
}
export default {
GetallWorkouts,
}
EDIT:
How the starup.cs Currently looks like
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 static void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapControllers();
});
}
}
When I did run my React in Chrome instead I got this Error instead:
net::ERR_CERT_AUTHORITY_INVALID
So it is something with the SSL as #sideshowbarker said so will look over that
This is the request from Devtool (?)
Declare AddCors() in ConfigureServices function and UseCors() in Configure function worked for me.
It should be like:
public void ConfigureServices(IServiceCollection services) {
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
}
The Configure function is changed depends on the version but this should work.
Try with do something like this:
services.AddCors(action =>
action.AddPolicy("AllowOrigins", builder =>
builder
//.WithOrigins("http://localhost:4200")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
)
);
tjhen in your:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowOrigins");
}

Angular API Call on C# Web API Cors Exception

I am trying to make an API Call on my C# Web API from my Angular Frontend.
I have tried it by HTTP and HTTPS.
HTTP: I am getting a CORS exception
HTTPS: I am getting a CONNECTION CLOSED EXCEPTION
I also have tried it via Postman and it worked so the Backend should not be the Problem.
I am using the Angular HTTP Client.
in your Startup.cs file in the ConfigureServices there must exist the following code
public void ConfigureServices(IServiceCollection services) method.
{
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder => builder
.WithOrigins("http://localhost:4200", "YOUR_REQUEST_ORIGIN_URI")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()));
}
Cors is security of browser, without cors configuration in api work it on postman, postman is not a web browser.
Try adding Cors configuration, on your api
[AspNet Web API]
Install package
Install-Package Microsoft.AspNet.WebApi.Cors
Edit WebApiConfig file, in App_Start/WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//change www.example.com for you domain, like localhost
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
}
}
[.Net Core]
Edit Startup.cs and add CORS middleware and service
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
//change www.example.com for you domain, like localhost
builder.WithOrigins("http://example.com");
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
References
AspNet WebApi
.Net Core

How to enable Cors in Signalr Azure Service

I am trying to use the Azure SignalR Service in a web app that only contains a hub class. When I try to access from another domain to the hub I get the following error
"Access to XMLHttpRequest at 'https://*/genericSocketHub/negotiate' from origin 'https://localhost:44303' 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.".
In the startup.cs class of my project I have:
` public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(o => o.AddPolicy("Policy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}));
services.AddSignalR().AddAzureSignalR(Configuration.GetConnectionString("AzureSignalRConnectionString")).AddJsonProtocol(options => options.PayloadSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() { ContractResolver = new DefaultContractResolver()});
services.AddSingleton(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCors("Policy");
app.UseAzureSignalR(routes =>
{
routes.MapHub<GenericSocketHub>("/genericSocketHub");
});
app.UseMvc();
}
}`
Without using Azure SignalR Service I didn't have any CORS issues
Try adding .WithOrigins("[THE_DOMAIN_TO_UNBLOCK]"); to your policy:
services.AddCors(o => o.AddPolicy("Policy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithOrigins("[THE_DOMAIN_TO_UNBLOCK]");
}));
Also make sure that you have the latest version of Microsoft.Asure.SignalR installed on the server along with the latest #aspnet/signalr installed on the client.
NOTE The signalr npm package is not compatible with Azure SignalR. I learned this the hard way..
The following worked for my setup which is Angular7, .NET CORE 2.1 and Azure SignalR. My setup looks like this:
ConfigureServices
// Add CORS
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod()
.WithOrigins("http://localhost:4200");
});
});
// Add Azure SignalR
services.AddSignalR().AddAzureSignalR();
Configure
app.UseCors("AllowAllOrigins");
app.UseAzureSignalR(routes =>
{
routes.MapHub<NextMatchHub>("/nextmatch");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "api/{controller=Home}/{action=Index}/{id?}");
});
NOTE Make sure that the various implementations are added in the same order as my example shows above. I cannot explain why it is sensitive about the order but this was also an issue on my end.

.NET Core UseCors() does not add headers

This would be a duplicate of How does Access-Control-Allow-Origin header work?, but the method there also isn't working for me. I'm hoping I'm just missing something.
I am trying to get a Access-Control-Allow-Origin header in my response from my .NET Core Web API, which I am accessing via AJAX.
I have tried several things. All, unless noted otherwise, have been in the Startup.cs file.
Method 1
As per the Microsoft Documentation:
public void ConfigureServices(IServiceCollection services)
{
// Add database
services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
// Add the ability to use the API with JSON
services.AddCors();
// Add framework services.
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetService<DbContext>().Database.Migrate();
serviceScope.ServiceProvider.GetService<DbContext>().EnsureSeedData();
}
}
app.UseCors(builder => builder.WithOrigins("https://localhost:44306").AllowAnyMethod());
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
Audience = Configuration["Authentication:AzureAd:Audience"],
});
app.UseMvc();
}
Method 2
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options => options.AddPolicy("AllowWebApp",
builder => builder.AllowAnyMethod()
.AllowAnyMethod()
.AllowAnyOrigin()));
//.WithOrigins("https://localhost:44306")));
// ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ...
app.UseCors("AllowWebApp");
// ...
}
I've also tried adding [EnableCors("AllowWebApp")] on both the Controller and Method.
From Postman, I get:
content-encoding → gzip
content-type → text/plain; charset=utf-8
date → Wed, 25 Jan 2017 04:51:48 GMT
server →Kestrel
status → 200
vary → Accept-Encoding
x-powered-by → ASP.NET
x-sourcefiles → =?UTF-8?B?[REDACTED]
I've also tried it in Chrome, and gotten similar headers.
If it matters, the method I'm trying to access has an Authorize attribute on it. But that part should be working fine (I'm at least getting a good response)
So, am I missing something very obvious, or did this get broken? I'm currently running version 1.1.0.
Edit adding JS and Controller Stub
function getContactPreviews(resultsCallback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
resultsCallback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.open("GET", "https://localhost:44357/api/User/ContactsPreview", true);
xmlhttp.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("AuthorizationToken"));
xmlhttp.send();
}
Controller Stub
[Authorize]
[Route("api/[controller]")]
public class UserController : ApiController
{
[HttpGet(nameof(ContactsPreview))]
[EnableCors("AllowWebApp")]
public IEnumerable<Customer> ContactsPreview()
{
// ...
}
}
The problem is that when using Bearer authentication (or any I would imagine), it adds a header "Authorization", and the server will only give an okay if the setup allows for that header.
There's two ways to solve the problem, and below is the only code needed. It goes in the Configure() method in Startup.cs in the Web API solution.
Method 1: Allow all headers
app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
.AllowAnyMethod()
.AllowAnyHeader());
Method 2: Allow specific headers
app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
.AllowAnyMethod()
.WithHeaders("authorization", "accept", "content-type", "origin"));
The extra headers are because, per the documentation:
Browsers are not entirely consistent in how they set Access-Control-Request-Headers. If you set headers to anything other than "*", you should include at least "accept", "content-type", and "origin", plus any custom headers that you want to support.
The Access-Control-Allow-Origin header is returned only if:
The request includes an "Origin" header.
The requested origin matches the CORS policy.
Then the server returns the ACAO-header with the origin URL as value.
The Origin header is usually set by the XMLHttpRequest object.
For more information, see How CORS works
In Startup.cs file, add following
public CorsPolicy GenerateCorsPolicy(){
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin(); // For anyone access.
//corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
corsBuilder.AllowCredentials();
return corsBuilder.Build();
}
In ConfigureServices method:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", GenerateCorsPolicy());
});
// To Apply CORS globally throughout the application
// In Configure method, add
app.UseCors("AllowAllOrigins");
[DisableCors]
Using DisableCors attribute, we can disable CORS for a controller or an action.
//To Enable CORS controller basis - If you apply globally you don't need this one.
[EnableCors("AllowAllOrigins")]
public class HomeController: Controller {}
In Startup.cs at the end of ConfigureServices() add this:
services.AddCors();
Then in Configure() at the top add this:
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("*"));
// alternatively you could use .With... methods to specify your restrictions:
// app.UseCors(x => x.WithOrigins("http://domain1.com").WithMethods("GET","POST").WithHeaders("Authorization").WithExposedHeaders("*"));
As of date 03/17/2019, .NET Core version 2.1:
This will possibly save some time to other poor souls...at some point I started to be frustrated and almost gave up on .NET Core WebApi as a separate project.
In real life circumstances, there are other configurations in Startup functions e.g. I had Swagger, DI registrations etc. I wasn't able to make bloody thing work until I put both AddCors() and UseCors() methods to be the first one getting called in configuration functions.
// 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("SomePolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("SomePolicy");
After that, calls from Angular 6 app (Swagger Typescript client calls) started to work as a charm.
I wasted hours on this problem today, only to discover it's because .Net Core 3 doesn't support preflight OPTIONS requests if you use the Endpoint routing RequirePolicy method of enabling CORS!
The official documentation does mention this, but it wasn't called out in an obvious warning block so I'd totally missed it.
The following will fix the problem, but it'll apply a global CORS policy, so caveat emptor!
Service Configuration:
public void ConfigureServices(IServiceCollection services)
{
string[] corsOrigins = Configuration.GetSection("AllowedHosts").Get<string[]>();
services.AddCors(options =>
{
options.AddPolicy("AllowConfiguredOrigins", builder => builder
.WithOrigins(corsOrigins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
});
...
Basically, don't do this:
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("AllowConfiguredOrigins");
});
...
...do this instead
Configure()
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors("AllowConfiguredOrigins");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
...
I want to add one more possibility for those who may have followed the advice above and it is still not working. In my case I was not getting the header returned (or only getting it on the first request) because of the order of registration in the pipeline.
I changed the order from this:
app.UseResponseCaching();
app.UseHttpsRedirection();
app.UseCors("WideOpen");
app.UseMvc();
To this:
app.UseCors("WideOpen");
app.UseResponseCaching();
app.UseHttpsRedirection();
app.UseMvc();
That resolved my issue.

CORS in .NET Core

I am trying to enable CORS in .NET Core in this way:
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
However, when I am sending a request to my app with Angular 2 I am getting the famous
"No 'Access-Control-Allow-Origin' header is present on the requested
resource."
error message.
I am also using Windows Authentication + WebListener.
If I am checking with postman the only response headers are:
Content-Length →3533
Content-Type →application/json;
charset=utf-8
Date →Fri, 14 Oct 2016 12:17:57
GMT Server →Microsoft-HTTPAPI/2.0
So there must be still something wrong configured. Any proposals?
If I remove the outcommented line it works, but I need Windows Authentication :-(
var host = new WebHostBuilder()
.UseWebListener()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
//.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM)
.Build();
Assume you have the answer, but for the benefit of searchers, I had the same problem with the standard tutorial on .NET Core Cors.
One of the many errors encountered:
XMLHttpRequest cannot load localhost:64633/api/blogs. Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'localhost:56573' is therefore not allowed
access. The response had HTTP status code 500.
After playing around, the following code worked. Full class posted below to aid understanding of what goes where.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Cors.Infrastructure;
namespace NetCoreWebApiTesting
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
// ********************
// Setup CORS
// ********************
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin(); // For anyone access.
//corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end!
corsBuilder.AllowCredentials();
services.AddCors(options =>
{
options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
// ********************
// USE CORS - might not be required.
// ********************
app.UseCors("SiteCorsPolicy");
}
}
}
To use it you can add the EnableCorsAttribute either on the controller or on the method. e.g.
[EnableCors("SiteCorsPolicy")]
[Route("api/[controller]")]
public class BlogsController : Controller
{
}
or
// POST api/value
[EnableCors("SiteCorsPolicy")]
[HttpPost]
public HttpResponseMessage Post([FromBody]Blog value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
When I called this using the following code (using standard js/jQuery for easy of copy and paste), the communication stopped being rejected.
function HandleClick() {
var entityData = {
"blogId": 2,
"url": "http://blog.com/blog1",
"posts": [
{
"postId": 3,
"title": "Post 1-1",
"content": "This is post 1 for blog 1",
"blogId": 2
},
{
"postId": 4,
"title": "Post 1-2",
"content": "This is post 2 for blog 1",
"blogId": 2
}
]
};
$.ajax({
type: "POST",
url: "http://localhost:64633/api/blogs",
async: true,
cache: false,
crossDomain: true,
data: JSON.stringify(entityData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (responseData, textStatus, jqXHR) {
var value = responseData;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
}
This way works normally, just tried it on angular2 with .net core.
The issue the OP is having is that this doesnt work with windows authentication. I am assuming the middleware for windows authentication is happening before a request comes through, in which case its breaking. Best bet would be to see if there is a way to enable the windows auth middleware after the cors middleware has processed in Configure.
Then the order would be
App.UseCors()
App.UseWindowsAuth()
App.UseMVC()
They must happen in this order for it to work.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
What the documentation misses, is the importance of .AllowAnyMethod(). If not present, the dreaded No 'Access-Control-Allow-Origin' will keep bugging you. In your code it's there, so I guess you missed setting the right header in jour client side application.
I Personally got it to work by allowing all:
app.UseCors(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
And my Angular post function like:
post(model) {
let headers = new Headers({
'Content-Type':'application/json; charset=utf-8;'
,'Accept':'*/*'
});
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(model);
return this.http.post(
'http://localhost:58847/api/TestPost', body, options)
.map((response: Response) => {
let res = response.json();
return res;
}
);
}
After that, you gradually work your way up by specifying origins etc.
In ASPNET CORE 2.0, The following works for me
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:5000").AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc()
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
Add this section in appsettings.json
"App": {
"CorsOrigins": "http://yourdomain"
}
and
services.AddCors(options => {
options.AddPolicy(DefaultCorsPolicyName, builder => {
builder.WithOrigins(
_appConfiguration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
).SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
Note: App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
You just need to add this in ConfigureService Method of StartUp Class
services.AddCors ();
and this in Configure Method of Startup Class and it will work fine then
app.UseCors (builder => builder
.AllowAnyOrigin ()
.AllowAnyHeader ()
.AllowAnyMethod ());
There is nothing more to add to enable CORS in .Net Core
I just fixed my problem with Cors in Core 3.1. I was following almost every example and documentation out there. Unfortunately nothing worked until I did .Build() for the builder inside the AddPolicy portion.
services.AddCors(options => {
options.AddPolicy(
name: OrginPolicyKey,
builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.Build() // <--- This right here
);
});
Also, other people were mentioning about calling the UseCors(OrginPolicyKey) before the rest of your routing and UseMvc stuff. That is correct and I saw that Putting UseCors after the route part broke it. Below is how mine is setup.
app.UseCors(OrginPolicyKey); // <--- First
// Then routing stuff..
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints
.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
Who knew a builder needs to be built ;D
I encountered CORS issues in my application. I felt that I properly implemented the logic but was still getting presented with Access-Control-Allow-Origin 403 Error. I tried every setting mentioned above but nothing worked.
I later discovered that my issue wasn't CORS related. I implemented a custom attribute
[Route("v1/[Controller]")]
[ServiceFilter(typeof(MyCustomFilterAttribute))]
public class MySpecialListsController
Calls made to the controller were properly making it to the method OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext context)
The logic within the filter was throwing an exception and was presented as a CORS 403 error.
The answer of #HockeyJ is right, but you can do something more concise if wanted.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Or if you want to chose what to include
services.AddMvcCore()
.AddCors()
(...)
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Cors
app.UseCors(builder =>
{
builder.AllowAnyHeader();
builder.AllowAnyMethod();
builder.AllowCredentials();
builder.AllowAnyOrigin(); // For anyone access.
//corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url.
});
}
this is actually is a bug in dotnet core.
try to add cors policy right in the "Configure" method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors(option =>
option.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
}

Categories