繁体   English   中英

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

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

我在 localhost:5599 上创建了一个带有 swagger 接口的 API。 如果我对 localhost:5599/api/owner 执行 GET 我得到所有者的 JSON,一切正常。

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

调用 localhost:5599/api/owner 给出:无法加载资源:net::ERR_CONNECTION_REFUSED

这是有道理的,因为 API 项目没有“运行”,但我怎样才能使它工作? 我应该在哪个 startup.cs 文件中放什么? 我是否需要在端点中以某种方式将这个 angular 项目“连接”到 API 启动? 非常感谢所有帮助!

这是 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");
    }
  });
 }
}

这些来自 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);

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

如果还有其他我想念的东西,很高兴听到! 格特斯

由于您提到 API 在不同端口上运行,因此请确保更改 Angular 应用程序上的 URL。

您还需要在 DotNet API 上配置 CORS,您可以这样做,

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM