我有一个控制台应用程序( NET Core 2.2 ),该应用程序的主要功能在cli中。但我想在其上调用rest api端点(以获取有关此应用程序的一些信息)。现在,我将代码实现到Program.cs中,添加一个Startup.cs和一个控制器。但是我无法通过邮递员联系我的管理员。缺少什么?
Program.cs:
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
// further logick...
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5002");
Startup.cs:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddBusinessComponents();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
控制器:
[Produces("application/json")]
[Route("cli/v1/dataPicker/info")]
public class InfoController : Controller
{
private IInfoBusinessComponent BusinessComponent { get; }
[Microsoft.AspNetCore.Mvc.HttpGet]
public async Task<IActionResult> GetInfoAsync()
{
Statuses statuses = null;
try
{
statuses = await BusinessComponent.GetInfo();
}
catch (System.Exception ex)
{
return BadRequest($"Exception occurred while trying to get health informations.");
}
return Ok(statuses);
}
}
答案 0 :(得分:0)
尝试:
[Route("api/[controller]")]
[ApiController]
public class InfoController : Controller
{
[HttpGet("GetInfo")]
public async Task<IActionResult> GetInfoAsync()
{
Statuses statuses = null;
try
{
statuses = await BusinessComponent.GetInfo();
}
catch (System.Exception ex)
{
return BadRequest($"Exception occurred while trying to get health informations.");
}
return Ok(statuses);
}
}
并在浏览器中调用它,如:
http://localhost:5002/api/Info/GetInfo
答案 1 :(得分:0)
我需要在launchSettings.json中添加行(launchBrowser和applicationUrl):
{
"profiles": {
"DataPicker.Cli": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"Key": "Value",
"ASPNETCORE_ENVIRONMENT": "Development"
}
"applicationUrl": "http://localhost:5003/"
}
}
}
现在,我可以通过浏览器甚至是Swagger来访问我的API。 :-)