【发布时间】:2021-08-08 17:35:06
【问题描述】:
https://i.imgur.com/JphyUEv.png
在观看此 YouTube 视频 https://youtu.be/PlW9dgU_aVM 之后,了解如何在 ASP.NET CORE 应用程序中设置实体框架核心数据库的第一个 CRUD 操作。
此时https://youtu.be/PlW9dgU_aVM?t=578在处理请求时发生了未处理的异常,我该如何解决这个问题(参考上图)。
P.S 抱歉阅读和破译
这是 REST Api 在 ASP.NET CORE 应用程序中使用实体框架核心数据库的第一个 CRUD 操作。
项目包括 ASP.NET Core 2.2 Web 应用,Entity Framework 2.2 版,Web 应用(模型-视图-控制器)
我使用本地数据库来生成模型和控制器,看看它是否与防火墙或其他连接问题有关,但我 99% 确定它是我的代码... 我是一名初级开发人员 => 没有高级/干净的基础 =<.>
//Users Model - Auto generated
namespace Demo_Api.Models
{
public partial class Users
{
public int Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public string Address { get; set; }
}
}
//UsersContext - Auto generated - snip
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Demo_Api.Models
{
public partial class UsersContext : DbContext
{
public UsersContext()
{
}
public UsersContext(DbContextOptions<UsersContext> options)
: base(options)
{
}
public virtual DbSet<Users> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("server=(localdb)\\MSSQLLocalDB;Database=Users; Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.6-servicing-10079");
modelBuilder.Entity<Users>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Address).HasMaxLength(10);
entity.Property(e => e.Name).HasMaxLength(10);
entity.Property(e => e.Number).HasMaxLength(10);
});
}
}
}
// UsersController - Auto generated - snip
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Demo_Api.Models;
namespace Demo_Api.Controllers
{
public class UsersController : Controller
{
private readonly UsersContext _context;
public UsersController(UsersContext context)
{
_context = context;
}
// GET: Users
public async Task<IActionResult> Index()
{
return View(await _context.Users.ToListAsync());
}
// GET: Users/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users
.FirstOrDefaultAsync(m => m.Id == id);
if (users == null)
{
return NotFound();
}
return View(users);
}
// GET: Users/Create
public IActionResult Create()
{
return View();
}
// POST: Users/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Number,Address")] Users users)
{
if (ModelState.IsValid)
{
_context.Add(users);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(users);
}
// GET: Users/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users.FindAsync(id);
if (users == null)
{
return NotFound();
}
return View(users);
}
// POST: Users/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Number,Address")] Users users)
{
if (id != users.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(users);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UsersExists(users.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(users);
}
// GET: Users/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users
.FirstOrDefaultAsync(m => m.Id == id);
if (users == null)
{
return NotFound();
}
return View(users);
}
// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var users = await _context.Users.FindAsync(id);
_context.Users.Remove(users);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool UsersExists(int id)
{
return _context.Users.Any(e => e.Id == id);
}
}
}
//StartUp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Demo_Api
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
预期和实际结果:拥有一个 REST Api,我可以通过影响现有数据库来执行 CRUD 操作。
处理请求时发生未处理的异常。 InvalidOperationException:无法解析类型的服务 'Demo_Api.Models.UsersContext' 尝试激活时 'Demo_Api.Controllers.UsersController'。
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
【问题讨论】:
-
您的屏幕截图显示了对
api/RasterCells的调用,但您的代码是关于用户的?你能分享正确的代码和/或截图吗?此外,标题(和屏幕截图)给出了另一个例外,而不是你引用的那个...... -
你提到的两个错误(截图和评论)是不同的。对于多个端点匹配问题,请验证 RasterCells 控制器中的所有路由。为了获得更好的帮助,请在您的问题中添加 RasterCells 控制器的代码。
-
所以你有两个错误:1)无法解析 UsersContext 2)重复的路线。对于 1,注册您的
UsersContext和对于 2) 我们需要查看RasterCells的控制器,但这些应该是单独的问题与信息,以便我们提供适当的答案 -
@intrixius 错误的屏幕截图,我的错。编辑了图像干杯
-
似乎是您的 UserContext 的 IoC 注册问题。您的 Startup.cs 文件是什么样的?
标签: c# sql-server asp.net-core asp.net-web-api