如何解决"AmbiguousMatchException:该请求匹配了多个端点". [英] How to fix "AmbiguousMatchException: The request matched multiple endpoints."
问题描述
处理请求时发生未处理的异常.InvalidOperationException:无法解析类型的服务尝试激活时出现"Demo_Api.Models.UsersContext"'Demo_Api.Controllers.UsersController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvidersp,Type type,Type requiredBy,bool isDefaultParameterRequired)
您的UsersContext似乎没有连接到Asp.net的服务"容器.
如果打开 Startup.cs
文件并查找 ConfigureServices
函数,则需要在此处连接数据上下文.
这是一个从Microsoft文档中提取的示例:
public void ConfigureServices(IServiceCollection服务){services.AddDbContext< BloggingContext>(options => options.UseSqlite("Data Source = blog.db")));}
但是,您的外观会更像:
public void ConfigureServices(IServiceCollection服务){services.AddDbContext< UsersContext>(options => options.UseSqlServer("server =(localdb)\\ MSSQLLocalDB; Database = Users; Trusted_Connection = True;")));}
要给出更多信息,这是告诉Asp.net如何解析在Controller的构造函数中指定的类.有关更多信息,请搜索依赖项注入或控制反转(IoC)主题.这些是用于实现此功能的技术.
https://i.imgur.com/JphyUEv.png
After following this YouTube video https://youtu.be/PlW9dgU_aVM going through how to setup entity framework core database first CRUD operations in ASP.NET CORE Application.
At this point https://youtu.be/PlW9dgU_aVM?t=578 an unhandled exception occurred while processing the request, how do I go about fixing the problem (Ref image above).
P.S sorry for read and deciphering
This is for a REST Api using entity framework core database first CRUD operations in ASP.NET CORE Application.
Project consists of ASP.NET Core 2.2 Web Application, Entity Framework version 2.2, Web Application (Model-View-Controller)
I've used a local DB for generating models and controllers to see if its to do with firewall or other connection problems, but I'm 99% sure its my code... i'm a junior developer => with no senior/clean foundation =<.
//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?}");
});
}
}
}
Expected and actual result: having a REST Api which I can do CRUD operations through affecting an existing DB.
Error messages:
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Demo_Api.Models.UsersContext' while attempting to activate 'Demo_Api.Controllers.UsersController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
It looks like your UsersContext is not wired up to the Services container for Asp.net.
If you open your Startup.cs
file and look for your ConfigureServices
function you are going to want to wire up your datacontext in here.
this is an example pulled from the microsoft docs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}
However, yours would look more like:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UsersContext>(options => options.UseSqlServer("server=(localdb)\\MSSQLLocalDB;Database=Users; Trusted_Connection=True;"));
}
To give a bit more information, this is telling Asp.net how to resolve the class in which you are specifying in the constructor of the Controller. For more information search for the topic of Dependency Injection or Inversion of Control (IoC). These are the techniques being used to achieve this functionality.
这篇关于如何解决"AmbiguousMatchException:该请求匹配了多个端点".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!