CORS in .net Core application isn't working - c#

I have .Net Core application with angular 2 cli. I am trying to call my controller action from the different port, I know that I can use CORS to make that work, but it is not working. has anyone the idea what could be the problem? thank you!

Your current configuration is allowing the wrong origin (HTTPS and not HTTP).
//Optional - called before the Configure method by the runtime
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
});
)
}

Related

c# SoapCore how to implement wildcard route

I'm using the SoapCore Nuget package to have a soap service on .Net Core. Below is the Configure method from Startup.cs that works great serving a Soap service. My challenge is that I want the service to be used with a service url that includes wildcards in the url path.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
app.UseSoapEndpoint<IpublishService>("/SoapService.asmx", new SoapEncoderOptions(), SoapSerializer.XmlSerializer);
}
The service works great in Postman using http://localhost:49154/SoapService.asmx but as I mentioned I would like to call it with wildcards like http://localhost:49154/AnyName1/AnyName2/SoapService.asmx
AnyName1 and AnyName2 can be any alpha text.
Thanks in advance for any suggestions.

CORS error after upgrade from .NET Core 3.1 to .NET 6

I recently upgraded a relatively large web API from .NET Core 3.1 to .NET 6 and am getting a no Access-Control-Allow-Origin header CORS error. I have not moved to the minimal hosting model, but I understand from the docs that this is not necessary and the old model should continue to work. I include code from startup and program below and what I had to change to make the upgraded project work. Note that everything else works properly.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod()
.WithOrigins(Configuration.GetSection("AllowedOrigins").Get<string[]>())
.SetIsOriginAllowed(origin => true)
.AllowAnyHeader();
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IHostApplicationLifetime appLifetime)
{
app.UseCors("CorsPolicy");
}
Note that * is returned from "AllowedOrigins".
Program.cs
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls(Configuration.GetValue<bool>("App:UsesHttps")
? $"{Configuration.GetValue<string>("App:HttpUrl")}, " +
$"{Configuration.GetValue<string>("App:HttpsUrl") }"
: $"{Configuration.GetValue<string>("App:HttpUrl")}")
.UseStartup<Startup>();
});
For the upgrade to .NET 6, nothing in Startup.cs has changed. In Program.cs, .UseUrls does not work anymore and instead I have it defined in appsettings and I have removed the call to .UseUrls.
Appsettings (.NET Core 3.1)
"App": {
"UsesHttps": false,
"HttpUrl": "http://0.0.0.0:5005",
"HttpsUrl": "https://0.0.0.0:5001"
},
Appsettings (.NET 6)
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5005"
}
}
},
Nothing else in the code has changed, and all I have done is update packages. I fail to see how they would influence a CORS error.
The app is running in a Docker container behind Nginx serving as a reverse proxy. I have not made any changed to the Nginx settings. The app is listening on HTTP only as Nginx handles the HTTPS connection. Again, this works when the app is built against .NET Core 3.1. I have read the documentation about upgrading to .NET 6 and I cannot find anything that would explain this kind of a change.
don't know if this will help you. We have the following in our API in the program.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other code left out here
app.UseAuthentication();
// Allow CORS for any origin, method or header
app.UseCors(policy =>
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthorization();
}
If I remember correctly the order of things is pretty important. I don't see Authentication and Authorization in your code. Don't know if you need that or not. There's a remark at this code as it might be allowing too much. We still have to investigate that.

.Net Core API returning 500 Internal Server Error

I have a .NET core web api. It works as expected when requesting from Postman but returning
Status Code: 500 Internal Server Error
Referrer Policy: strict-origin-when-cross-origin
when requested from other React JS client. I have already enabled CORS in the Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
...
}
But still getting the Status Code: 500 Internal Server Error. I have been trying to solve this issue for too long. Please help. Thanks.
add this in your configure method:
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
if its not solved then add a custom middleware and check your request you can use ilogger for logging exception.
follow this link for middleware: https://www.tutorialsteacher.com/core/how-to-add-custom-middleware-aspnet-core

Restricting origins with Cors and Owin token authentication

Ive managed to enable Cors fine and my client application communications to my web API application using AJAX. The problem is its open to any host now. I added the following line to Startup.Auth.cs:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
I was using the standard WebApi method for cors, but had problems when issuing token authentication.
My question is how do i restrict origins using this method?
You can restrict the origin using CorsPolicyBuilder Class
app.UseCors(builder =>
builder.WithOrigins("http://localhost", "https://localhost"));
Define one or more named CORS policies, and then select the policy by name at run time
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
...
}
You can read how to define CORS at here.

ASP.NET MVC 6 AspNet.Session Errors - Unable to resolve service for type?

Alright, so recently I've been having a lot of trouble using the new Microsoft.AspNet.Session middleware for ASP.NET vNext (MVC 6). The error I'm getting,
Unable to resolve service for type
'Microsoft.Framework.OptionsModel.ConfigureOptions[Microsoft.AspNet.Session.SessionOptions]
while attempting to activate
'Microsoft.AspNet.Session.SessionMiddleware'
occurs on all pages regardless of session use. The DNVM version I'm using is Beta5 x86 and all the packages in the project are Beta5 as well. The project itself is an attempt at porting an ASP.NET MVC 5 project to MVC 6 without much luck. Below are links to resources that may be important:
Project.json: http://tinyurl.com/project-json
Startup.cs: http://tinyurl.com/startup-cs
It seems to be a problem with my configuration but I'm not sure what to do about it... Pls send help Dx
Unable to resolve service for type 'Microsoft.AspNetCore.Session.ISessionStore' while attempting to activate 'Microsoft.AspNetCore.Session.SessionMiddleware'
If you get this error message in ASP.NET Core, you need to configure the session services in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddSessionStateTempDataProvider();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
This code helps you...
In Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
....
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);//We set Time here
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvc();
}
Thanks!!!
you can add session middleware into configure method in the startup.
public void ConfigureServices(IServiceCollection services) {
services.AddSession();
services.AddMvc();
}
Step 1: Install "Microsoft.AspNetCore.Session" this package.
Step 2: Add these functions in configure services function in the startup file.
(1). services.AddSession();
(2). services.AddDistributedMemoryCache();
Step 3: Add "app.UseSession()" use session function in Configure function in the startup file.
ASP.NET CORE 6.0
In program.cs file add this
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(1800);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
Then
app.UseSession();
For more Read official doc
For ASP.NET 7 there is no longer a Startup.cs file, as it is merged with the Program.cs file. Instead add
builder.Services.AddSession();
builder.Services.AddDistributedMemoryCache();
above
var app = builder.Build();
Then you can add
app.UseSession();
I am using .net core 5 . I was getting the same issue
this is how i solved it
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddMvc();
}
I have added these and I have also added these ,
I added it to the startup.cs class
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
}
My problem is solved, I hope yours is solved too.
app.usesession() in the program.cs file; I deleted your method and it was fixed

Categories

Resources