【发布时间】:2021-07-19 17:50:09
【问题描述】:
我正在做一个简单的HTTP GET 操作,点击我的网址后,我会将人员数据显示为JSON
起初,一切正常
工作代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Apitest4.Models;
namespace Apitest4.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PeopleController : ControllerBase
{
[HttpGet]
public IEnumerable<Person> Get()
{
using (var context = new ModelContext())
{
return context.People.ToList();
}
}
}
}
您看到的上述代码是WeatherController (Visual Studio 2019) 的略微修改版本,我用它来制作我自己的PeopleController。这段代码给了我预期的正确的 API 响应
然后我想使用自动化方法来做同样的事情,因为我必须覆盖很多表
[对比代码:2019]
[控制器(右键单击)>添加>New Sacffolded Item>Api Controller with Actions using Entity Framework]
自动生成的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Apitest4.Models;
namespace Apitest4.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PeopleController : ControllerBase
{
private readonly ModelContext _context;
public PeopleController(ModelContext context)
{
_context = context;
}
// GET: api/People
[HttpGet]
public async Task<ActionResult<IEnumerable<Person>>> GetPeople()
{
return await _context.People.ToListAsync();
}
}
}
这段代码给了我这个错误:
InvalidOperationException: Unable to resolve service for type 'Apitest4.Models.ModelContext' while attempting to activate 'Apitest4.Controllers.PeopleController'.
完整的错误信息:
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Apitest4
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
虽然我是 .net 的新手,但我就是不明白,为什么它没有正确获取上下文?我没有更改任何导入。请指出我的错误。
TIA
【问题讨论】:
-
嗨@Frost,这个错误信息意味着你没有注册服务。请分享您的 Startup.cs。
-
@Rena 添加了 startup.cs
标签: asp.net asp.net-mvc entity-framework asp.net-core asp.net-web-api