在ASP.NET Core中,通过调用其他项目的端点是很常见的任务。你可以按照以下步骤来实现:
例如:
"OtherProjectUrl": "http://localhost:5001"
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGet("/otherproject", async context =>
{
var otherProjectUrl = Configuration["OtherProjectUrl"];
var client = new HttpClient();
var response = await client.GetAsync($"{otherProjectUrl}/api/endpoint");
var content = await response.Content.ReadAsStringAsync();
await context.Response.WriteAsync(content);
});
});
}
这个操作将启动一个新的端点("/otherproject"),使用HttpClient从其他项目读取数据。
注意:如果你使用的是HTTPS而不是HTTP,请使用“UseHttps”替换“UseHttp”方法。