You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC Core 2.0仅Delete操作无法解析注入的CompanyDbContext问题

Troubleshooting the DI Resolution Error for Delete Action in ASP.NET Core 2.0

Let's break down why your Delete action is throwing that InvalidOperationException while all other controller actions work perfectly. The critical clue here is that the error happens when activating the PersonsController (not during the execution of the Delete method), so we need to focus on how the controller is being instantiated via dependency injection.

1. Verify the PersonsController Constructor

Since PersonsController inherits from BaseController (which relies on constructor injection for CompanyDbContext), you must ensure your controller explicitly calls the base constructor with the injected context. If you have an accidental parameterless constructor or miss the base call, DI will fail to resolve the context.

Correct Constructor Example:

public class PersonsController : BaseController
{
    // Ensure only this constructor exists (no parameterless variants)
    public PersonsController(CompanyDbContext db) : base(db)
    {
    }

    // Your action methods...
}
  • If you have multiple constructors (e.g., a parameterless one for testing), the DI container may pick the wrong one, leading to the context not being injected. Remove any unnecessary constructors.

2. Validate CompanyDbContext Registration & Implementation

Double-check that your CompanyDbContext is set up correctly for DI:

  • Ensure the context has a public constructor accepting DbContextOptions<CompanyDbContext>:
    public class CompanyDbContext : DbContext
    {
        public CompanyDbContext(DbContextOptions<CompanyDbContext> options) : base(options)
        {
        }
    
        public DbSet<Person> Persons { get; set; }
        // Other DbSets...
    }
    
  • Confirm your Startup.ConfigureServices doesn't wrap the AddDbContext call in a conditional that might exclude it (e.g., only in development mode):
    public void ConfigureServices(IServiceCollection services)
    {
        // This should be unconditional
        services.AddDbContext<CompanyDbContext>(options => 
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddMvc();
    }
    

3. Check Middleware Order in the Request Pipeline

In ASP.NET Core, middleware order matters. If middleware that creates the request scope (like MVC) is placed incorrectly, it can break DI for specific request types. Ensure your Configure method follows this order:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Place CORS/Authentication middleware BEFORE UseMvc
    app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    app.UseAuthentication();

    // UseMvc should be the last middleware in most cases
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "api/{controller}/{action}/{id?}");
    });
}
  • Misordered middleware can prevent the request scope from being created properly for DELETE requests, even if it works for other HTTP methods.

4. Test the Delete Action Directly (Bypass HttpClient)

The issue might be with how your HttpClient is sending the DELETE request, not the controller itself. Use a tool like Postman or curl to send a direct DELETE request to http://your-api-url/api/persons/{id}:

  • Verify the request method is indeed DELETE (not OPTIONS or another method).
  • Ensure the URL matches your route template exactly (including the id parameter).
    If the direct test works, your HttpClient code has a bug (e.g., incorrect method or URL).

5. Rule Out Custom Controller Activation Logic

If you've added a custom IControllerActivator to your DI container, it might be overriding the default DI behavior for controller instantiation. Check Startup.ConfigureServices for any code like this:

// Remove this if present, unless you've explicitly configured it to handle DI correctly
services.AddSingleton<IControllerActivator, CustomControllerActivator>();

6. Consider ASP.NET Core 2.0 Known Issues

ASP.NET Core 2.0 has a few bugs related to scoped services and request handling. If none of the above fixes work, consider upgrading to ASP.NET Core 2.1 or later (which is LTS and includes bug fixes for DI and request scoping).


内容的提问来源于stack exchange,提问作者ProfK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:21:40