简体   繁体   English

.NET Core 3.0 Web API 连接问题上的 Angular SPA

[英]Angular SPA on .NET Core 3.0 Web API Connection issues

I made an API with a swagger interface, on localhost:5599.我在 localhost:5599 上创建了一个带有 swagger 接口的 API。 If I do a GET to localhost:5599/api/owner i get a JSON of owners, everything works.如果我对 localhost:5599/api/owner 执行 GET 我得到所有者的 JSON,一切正常。

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).我想要采取的下一步是制作一个 Angular 界面,所以我在解决方案中添加了一个带有 Angular 模板的 webproject,将 webproject 设置为启动项目(localhost:49960 是应用程序 url;但是使用 ssl 44376 并且应用程序运行使用最后一个端口)。

Calling localhost:5599/api/owner gives: Failed to load resource: net::ERR_CONNECTION_REFUSED调用 localhost:5599/api/owner 给出:无法加载资源:net::ERR_CONNECTION_REFUSED

This makes sense as the API project is not "running", but how can I make this work?这是有道理的,因为 API 项目没有“运行”,但我怎样才能使它工作? In which startup.cs file should i put what?我应该在哪个 startup.cs 文件中放什么? Do I need to "connect" this angular project to the API startup somehow in endpoints?我是否需要在端点中以某种方式将这个 angular 项目“连接”到 API 启动? All help is much appreciated!非常感谢所有帮助!

This is the startup.cs for the Angular WebApp这是 Angular WebApp 的 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.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这些来自 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 Angular 中 fetch-owners-component 的构造函数

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/ API_BASE_URL 是 http:localhost:5599/

If there is something else I'm missing, would be glad to hear!如果还有其他我想念的东西,很高兴听到! Grts格特斯

Since you mentioned that API runs on different port make sure to change the URL on the Angular app.由于您提到 API 在不同端口上运行,因此请确保更改 Angular 应用程序上的 URL。

Also you need to configure CORS on the DotNet API, you can do it as,您还需要在 DotNet API 上配置 CORS,您可以这样做,

app.UseCors(builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed((host) => true)
                .AllowCredentials()
            );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 SPA 添加到 .NET 内核 Web API - Adding SPA to .NET Core Web API 在部署时使用 .NET 核心调用 api Angular Spa 时出错 - Error calling api Angular Spa with .NET Core on deployment 如何为我的 React/.NET Core 3.0 SPA web 应用程序添加 Microsoft Identity/Azure AD 登录功能 - How to add Microsoft Identity/Azure AD login feature for my React/.NET Core 3.0 SPA web application 在 ASP.NET Core 3 (3.0) SPA (Angular) 中如何正确检查用户角色? - In ASP.NET Core 3 (3.0) SPA (Angular) how to properly check for user roles? 基本 Angular SPA 与 .NET Web ZDB974238714CA8DE634A7CE1SSOD083A14FZ 连接 - 实现 - Basic Angular SPA connected with .NET Web API - implement SSO 使用.NET web api路由使用Angular SPA投掷404 - Getting .NET web api route to work with Angular SPA throwing 404 .net核心Web API关闭数据库连接 - .net core web api close database connection 如何在多台服务器上发布 Web API net core 3.0 - How to Publish a Web API net core 3.0 in multiple servers ASP.NET Core 3.0 Web API 路由不起作用 - ASP.NET Core 3.0 Web API routing not working CORS 停止 Angular 应用程序和 .NET CORE 3.0 ZDB974238714CA8DE634A7CE1D083A1 之间的通信 - CORS stopping communication between Angular app and .NET CORE 3.0 API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM