0

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.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197

2 Answers2

1

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()));
}
Alessio Marzoli
  • 167
  • 2
  • 3
  • 10
-1

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

  1. [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);
    }
}
  1. [.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