1

I made an API with a swagger interface, on localhost:5599. If I do a GET to localhost:5599/api/owner i get a JSON of owners, everything works.

Next step I want to take is make an Angular interface, so I added a webproject with Angular template to the solution, set the webproject as startup project (localhost:49960 is the app url; but with ssl 44376 and with the app running uses the last port).

Calling localhost:5599/api/owner gives: Failed to load resource: net::ERR_CONNECTION_REFUSED

This makes sense as the API project is not "running", but how can I make this work? In which startup.cs file should i put what? Do I need to "connect" this angular project to the API startup somehow in endpoints? All help is much appreciated!

This is the startup.cs for the Angular WebApp

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();
  // In production, the Angular files will be served from this directory
  services.AddSpaStaticFiles(configuration =>
  {
    configuration.RootPath = "ClientApp/dist";
  });
}

// 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("/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.UseHttpsRedirection();
  app.UseStaticFiles();
  if (!env.IsDevelopment())
  {
    app.UseSpaStaticFiles();
  }

  app.UseRouting();

  app.UseEndpoints(endpoints =>
  {
    endpoints.MapControllerRoute(
              name: "default",
              pattern: "{controller}/{action=Index}/{id?}");
  });

  app.UseSpa(spa =>
  {
          // To learn more about options for serving an Angular SPA from ASP.NET Core,
          // see https://go.microsoft.com/fwlink/?linkid=864501

          spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
      spa.UseAngularCliServer(npmScript: "start");
     // spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
    }
  });
 }
}

These snippets from API startup.cs

services.AddCors(options =>
  {
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
  });  

app
      .UseCors("CorsPolicy")
      .UseHttpsRedirection()
      .UseRouting()
      .UseEndpoints(config => config.MapControllers())
      .UseSwagger()
      .UseSwaggerUI(config => config.SwaggerEndpoint("v1/swagger.json", "VerticalSliced.DogFaceAPI - V1"))
      .UseStaticFiles();    

services
      .AddMediatR(cfg => cfg.AsScoped(), typeof(ToDoItemsQueryHandler).GetTypeInfo().Assembly)
      .AddMediatR(cfg => cfg.AsScoped(), typeof(OwnersQueryHandler).GetTypeInfo().Assembly)
      .AddMediatR(cfg => cfg.AsScoped(), typeof(DogsQueryHandler).GetTypeInfo().Assembly)
      .AddMediatR(cfg => cfg.AsScoped(), typeof(MediaFilesQueryHandler).GetTypeInfo().Assembly)
      .AddMediatR(cfg => cfg.AsScoped(), typeof(MedicalFilesQueryHandler).GetTypeInfo().Assembly)
      .AddSwaggerGen(config => config.SwaggerDoc("v1", new OpenApiInfo { Title = "VerticalSliced.DogFaceAPI", Version = "v1" }))
      .AddControllers()
      .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

The constructor for the fetch-owners-component in Angular

constructor(http: HttpClient, @Inject('API_BASE_URL') apiBaseUrl: string) {
http.get<UIOwner[]>(apiBaseUrl + 'api/owner').subscribe(result => {
  this.owners = result;
}, error => console.error(error));
}

API_BASE_URL is http:localhost:5599/

If there is something else I'm missing, would be glad to hear! Grts

BHANG
  • 354
  • 1
  • 5
  • 16
  • 1
    you said your dotnet api runs in different port – Sajeetharan Dec 24 '19 at 17:47
  • Does this answer your question? [Running two projects at once in Visual Studio](https://stackoverflow.com/questions/3850019/running-two-projects-at-once-in-visual-studio) – R. Richards Dec 24 '19 at 17:57
  • @Sajeetharan When I synchronise them I get Access to XMLHttpRequest at 'http://localhost:49960/api/dog' from origin 'https://localhost:44376' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Thanks for pointing out Brother, now I can move on – BHANG Dec 24 '19 at 17:59
  • @R.Richards I Don't know, I'll go with Sajeetharan his answer, pointing out my blurred vision mistake. Thanks for the effort though – BHANG Dec 24 '19 at 18:01
  • 1
    @BHANG check how to enable Cors on the api in the answer below – Sajeetharan Dec 24 '19 at 18:02

1 Answers1

1

Since you mentioned that API runs on different port make sure to change the URL on the Angular app.

Also you need to configure CORS on the DotNet API, you can do it as,

app.UseCors(builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed((host) => true)
                .AllowCredentials()
            );
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • 1
    https://stackoverflow.com/questions/56015934/no-access-control-allow-origin-header-in-asp-core-and-angular7 – Sajeetharan Dec 24 '19 at 18:04
  • Thank you so much for your effort! You worked hard for your points!! – BHANG Dec 24 '19 at 18:09
  • I'm still checking the code in your link for CORS. Atm I Still get a Access to XMLHttpRequest at 'http://localhost:49960/api/dog' from origin 'https://localhost:44376' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.. Looks to me like he can find and validate the resource so should be good! Its the first time I'm working with CORS, so I still have some reading to do (and trail-and-erroring)Thank you so much man! – BHANG Dec 24 '19 at 18:20
  • I think I'm missing that Interceptor from your link. No Class that adds a Access-Control-Allow-Origin header to the resource in my solution. I'm going to need some time for catching up on this, but big thanks to you my friend! Now I know what I'm missing :) – BHANG Dec 24 '19 at 18:43