我正在尝试进行API调用;我启动Visual Studio并在postman中输入以下内容:
http://localhost:51266/api/country
我在方法上设置了一个断点,但什么也没发生。404找不到了
这是控制器:
[Route("api/[controller]")]
[ApiController]
public class CountryController : Controller
{
private ICountryRepository countryRepository;
public CountryController(ICountryRepository repository)
{
this.countryRepository = repository;
}
[HttpGet]
public IActionResult GetCountries()
{
var countries = countryRepository.GetCountries().ToList();
return Ok(countries);
}
}
我做错了什么?
我在Startup
中有这个:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connectionString = Configuration["connectionStrings:bookDbConnectionString"];
services.AddDbContext<BookDbContext>(c => c.UseSqlServer(connectionString));
services.AddScoped<ICountryRepository, CountryRepository>();
}
我现在是这样的:
[ApiController]
public class CountryController : Controller
{
private ICountryRepository countryRepository;
public CountryController(ICountryRepository repository)
{
this.countryRepository = repository;
}
[HttpGet]
[Route("api/[controller]")]
public IActionResult GetCountries()
{
var countries = countryRepository.GetCountries().ToList();
return Ok(countries);
}
}
我的startup class:
public class Startup
{
public static IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connectionString = Configuration["connectionStrings:bookDbConnectionString"];
services.AddDbContext<BookDbContext>(c => c.UseSqlServer(connectionString));
services.AddScoped<ICountryRepository, CountryRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BookDbContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
}
}
如果我这样做:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BookDbContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseRouting();
app.UseMvc();
}
我得到了这样的警告:
警告MVC 1005
在使用端点路由时,不支持使用“JumeMvc”配置MVC。若要继续使用“MvcOptions.EnableEndpointRouting = false”,请在“ConfigureServices”中设置“MvcOptions.EnableEndpointRouting = false”。WebApplication2 D:\Mijn Documents\VisualStudio_2019\WebApplication2\WebApplication2\Startup.cs
3条答案
按热度按时间wz3gfoph1#
解决办法是这样的:
tcbh2hod2#
几种不同的方法来实现这一点
或
我最喜欢这个,我认为它是最直观的
如果这些都不起作用,那是因为您没有在
Startup.cs
中的Configure
方法中调用app.UseMVc
laximzn53#
问题是路线,它必须继续行动
或者,你可以保留控制器上的路由,只添加一个空的到动作: