[英]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.