3 回答
TA贡献2003条经验 获得超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条经验 获得超12个赞
结合不同的方法来实现这一目标
[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);
}
}
如果这些都不起作用,那是因为您没有在 中的 方法中调用 app.UseMVcConfigureStartup.cs
TA贡献1863条经验 获得超2个赞
问题是路线,必须继续行动
[HttpGet]
[Route("api/[controller]")]
public IActionResult GetCountries()
或者,您可以将路由保留在控制器上,然后将一个空路由添加到操作中:
[Route("")]
- 3 回答
- 0 关注
- 128 浏览
添加回答
举报