c# - .NET Core 3.0 Web API 连接问题上的 Angular SPA
问题描述
我在 localhost:5599 上制作了一个带有招摇接口的 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()
);
推荐阅读
- react-native - 无法生成签名的 APK 反应原生应用
- java - 一个对象,多个函数调用 - Python & Java
- rest - 如何保护 api rest symfony?
- javascript - mailto: 和 onclick() 在同一元素上的行为
- google-sheets - 当值由分隔符分隔时,如何在 Google 表格单元格中提取字符串?
- c++ - 如何改变c++应用程序的视觉效果?
- java - 在单独的线程上获取套接字数据,然后将其传递给主线程
- c# - 更改列表视图标签值
- php - 如何像在 Firebase (Android) 中一样在应用服务器中传递自定义数据 (web url)
- git - 如何仅在 Git 中恢复文件?