3 回答

TA貢獻2003條經(jīng)驗 獲得超2個贊
解決方案是這樣的:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
services.AddControllers(); //added this
var connectionString = Configuration["connectionStrings:bookDbConnectionString"];
services.AddDbContext<BookDbContext>(c => c.UseSqlServer(connectionString));
services.AddScoped<ICountryRepository, CountryRepository>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BookDbContext context) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting(); //uncommented
app.UseAuthorization(); //added this
app.UseEndpoints(endpoints => { //added this
endpoints.MapControllers();
});
//removed the app.UseMvc(); line
}

TA貢獻2012條經(jīng)驗 獲得超12個贊
結(jié)合不同的方法來實現(xiàn)這一目標
[Route("api/country")]
[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);
}
}
或者
[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);
}
}
我最喜歡這個,我認為它是最直觀的
[Route("api")]
[ApiController]
public class CountryController : Controller
{
private ICountryRepository countryRepository;
public CountryController(ICountryRepository repository)
{
this.countryRepository = repository;
}
[HttpGet("country")]
public IActionResult GetCountries()
{
var countries = countryRepository.GetCountries().ToList();
return Ok(countries);
}
}
如果這些都不起作用,那是因為您沒有在 中的 方法中調(diào)用 app.UseMVcConfigureStartup.cs

TA貢獻1863條經(jīng)驗 獲得超2個贊
問題是路線,必須繼續(xù)行動
[HttpGet]
[Route("api/[controller]")]
public IActionResult GetCountries()
或者,您可以將路由保留在控制器上,然后將一個空路由添加到操作中:
[Route("")]
- 3 回答
- 0 關(guān)注
- 199 瀏覽
添加回答
舉報