cors c# web API react - c#

(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");
}

Related

asp.net core none of the controllers are initialized

I have an ASP.NET project and everything is returning a 404, here's my startup 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.AddControllersWithViews();
}
// 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();
else
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapGet("/debug/routes", async ctx =>
{
await ctx.Response.WriteAsync(string.Join(", ", endpoints.DataSources.SelectMany(x => x.Endpoints)));
});
});
}
}
here's a sample controller:
public class Home : Controller
{
private readonly DatabaseContext _databaseContext;
public Home(DatabaseContext databaseContext)
{
Console.WriteLine($"Initialized home controller"); // This doesn't get called at all.
_databaseContext = databaseContext;
_databaseContext.Database.EnsureCreated();
}
[HttpGet("/home")]
public IActionResult Index()
{
ViewData["Products"] = _databaseContext.Products.ToList();
return View();
}
.....
and whenever I launch the server it I would go to /home and it would return 404, I also go to /debug/routes and it would show only the 2 endpoints inside the UseEndpoints function but never the controller classes I made
Try registering you db context in service as below. You could be getting error due to dependency of DatabaseContext on your HomeController would not be able to resolve.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add below line
services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connectionString));
services.AddControllersWithViews();
}
In the Configure(IApplicationBuilder app, IWebHostEnvironment env) method of the Startup class you need something like: app.MapControllers();
I think you controllers are registered to DI throught the call services.AddControllersWithViews(); but there is no middleware registration to invoke your controllers, wich should be done in the Configure method.

Static files works only on default endpoint ASP NET CORE MVC

Problem is that static files loads only on default endpoint .
If I type endpoint route manually static files won't load
I add ~ character to every script tag but it won't works
Same Page but on endpoint
When Type same controller and action on URL
Startup.cs
{
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.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true)
.AllowAnyHeader());
});
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Customer}/{action=Customers}/{id?}");
});
}
}
}```
Thank you for your advice
The problem was : When adding path some file I forget add ~(tilda)
It dumb but its true

Define different (than global) CORS policy for WEB API controller in .Net Core

I have a global CORS policy defined like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// global cors policy
app.UseCors("MyPolicy");
}
I must specify the global policy because I am using SignalR.
The policy allows the domain of the website.
In addition, I need to provide a limited number of endpoints for partners that have many different domains.
How do I allow a specific controller to be accessed from any origin (exclude from global policy and add custom policy)?
In StartUp.cs you could configure cors in ConfigureService
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
}
Then in Configure function you could configure the cors per mapped SignlR hub:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors();
...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
//Map each hub and ad RequireCors per hub
endpoints.MapHub<EchoHub>("echo")
.RequireCors(MyAllowSpecificOrigins);
endpoints.MapRazorPages();
});
}

Asp.net Core 3.0 CORS not working based on official documentation

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: Enable Cross-Origin Requests (CORS) in ASP.NET Core
Here it is my Startup.cs
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(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("localhost", "www.google.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
// 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();
});
}
}
And these are my response headers:
What should I set up for getting corret CORS headers in Response?
Here it is my fetch api test:
Oops, I successed to solve this.
This combination was the only one to me, what is working:
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(); //This needs to let it default
}
// 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(
options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
); //This needs to set everything allowed
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
If you put the API URL directly in the browser, CORS is not involved.
It isn't a cross-origin request.
That only happens when you have a page hosted at one origin, e.g. localhost:5000, which has JavaScript code that calls an API at origin localhost:5001.
(or otherwise fetches resources from another origin)
But in your case the only origin is the API origin and thus CORS is not needed.

CORS Headers missing from basic API response apnetnet core 3.0

I have just created a default dotnet core 3.0 API project with the basic weather forecast API. I wanted to get CORS working before I did anything else with the project.
In startup i have the following code....
private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// 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(MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
// 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.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
As you can see, I am not doing anything special or seemingly incorrect. This is directly from the MSDN documentation....
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.0
The problem is that when sending requests through both the browser and postman, There are none of the expected headers in the given responses.
I have googled the crap out of this and have not got anywhere. Am i missing something? could it be environmental? has it changed from a previous version of core?

Categories