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
Related
I want to use Http.sys to enable windows authentication and use POSTman to send GET request.
I already enter my computer's account and password,but POSTman told me this error.
Having no idea what happened,somebody can tell me the reason?
Configure Windows Authentication in ASP.NET Core
UPDATE
My Purpose
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "webwinauth", Version = "v1" });
});
}
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "webwinauth v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseHttpSys(options =>
{
options.Authentication.Schemes =
AuthenticationSchemes.NTLM |
AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = true;
});;
});
POSTman
Setting about NTLM
ERROR
Error
You cannot use Http.sys with asp.net core its not compatible with the ASP.NET Core Module and can't be used with IIS or IIS Express. You could have a look here if offical document.
Note: You could also have a look offical reference here
Update: Complete official sample you can download from here
Hope it would help you.
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.
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?
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.
I'd like to enable CORS on an API built with ASP.NET Core MVC, but all the current documents refer to earlier versions of that framework.
The notes on the new Cors features are very light, but I was able to get it working in my solution by looking at the new classes and methods. My Web API startup.cs looks like this. You can see how you can construct your origins and policies her by using the new CorsPolicy class. And enabling CORS with the AddCors and UseCors methods.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Add Cors support to the service
services.AddCors();
var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();
policy.Headers.Add("*");
policy.Methods.Add("*");
policy.Origins.Add("*");
policy.SupportsCredentials = true;
services.ConfigureCors(x=>x.AddPolicy("mypolicy", policy));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
//Use the new policy globally
app.UseCors("mypolicy");
// Add MVC to the request pipeline.
app.UseMvc();
}
You can also reference the policy in the controllers with the new attributes like so
[EnableCors("mypolicy")]
[Route("api/[controller]")]
I got it working using the following code:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()));
}
You can chain AllowAnyHeader() and/or AllowAnyMethod() to the configure action if needed.
To configure it for the complete app:
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowAll");
}
Or just for a controller:
[EnableCors("AllowAll")]
public class HomeController : Controller
{
// ...
}
--
Update: configuring CORS for all requests can be done a bit easier:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors();
}
public void Configure(IApplicationBuilder app)
{
app.UseCors(builder =>
{
builder.WithOrigins("http://some.origin.com")
.WithMethods("GET", "POST")
.AllowAnyHeader();
});
}
For more information, refer to the docs.
In the most recent RC2 of ASP.NET Core.
The NuGet packages are
"Microsoft.AspNetCore.Owin": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Cors": "1.0.0-rc2-final",
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(builder => builder
.AllowAnyOrigin());
app.UseMvc();
}
Support for CORS is currently in development. Following issue is tracking that:
https://github.com/aspnet/Mvc/issues/498
Update (3/28/2015):
This feature has been checked in and should be available in the next release.
cs1929 the method services.ConfigureCors(...) does no more exist. It is combined to AddCors:
services.AddCors(options =>
options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()));
Install : Microsoft.AspNetCore.Cors
In Configure method:
app.UseCors(builder =>
builder.WithOrigins("http://some.origin.com"));