尝试激活 'Student.Controllers.MyController' 时无法解析类型 'Microsoft.AspNetCore.Mvc.ActionContext' 的服务

Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.ActionContext' while attempting to activate 'Student.Controllers.MyController'

我正在尝试在我的控制器中使用 Microsoft.AspNetCore.Mvc.ActionContext,但即使我在 MyController 中执行了 DI,我仍然收到此错误。我不知道如何修复它,请帮忙

public class MyController : Controller
    {
        
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly ActionContext _actionContext;

        public StudentsController(
           IWebHostEnvironment hostEnvironment,
           ActionContext actionContext)
        {
            
            _hostEnvironment = hostEnvironment;
            _actionContext = actionContext;
        }

我在此处尝试访问控制器方法中的 ActionContext:

[HttpPost]
        public async Task<IActionResult> RegistrationPdf()
        {
            string wwwRootPath = _hostEnvironment.WebRootPath;
            ViewAsPdf pdf = new ViewAsPdf("RegistrationPdf")
            {
                FileName = "RegistrationPdf.pdf",
               
        };
        byte[] pdfData = pdf.BuildFile(_actionContext).Result;
        string fullPath = @"\Files\" + pdf.FileName;
        using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
        {
            fileStream.Write(pdfData, 0, pdfData.Length);
        }

      return RedirectToAction("Registration");
        


    }

StartUp.cs

namespace Student
{
    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.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders()
            .AddDefaultUI()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        
           
            services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireDigit = true;
                options.Lockout.AllowedForNewUsers = true;

            });

            services.ConfigureApplicationCookie(options =>
            {
               ptions.SlidingExpiration = true;
            });

            services.AddControllersWithViews();
            services.AddRazorPages(options =>
            {
                options.Conventions.AuthorizePage("/Students/StudentInfo/");
                options.Conventions.AuthorizeFolder("/Private");
            });

          
            services.AddDbContext<TrainingDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection2"));
                options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            });
                
                
            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });
           
        }

   
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
               
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication(); 
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapHub<ChatHub>("/chatHub");
            });
            RotativaConfiguration.Setup((Microsoft.AspNetCore.Hosting.IHostingEnvironment)env); 
        }
    }
}

像下面这样更改您的代码:

private readonly Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor actionContextAccessor;

public HomeController(Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor actionContextAccessor,IConfiguration configuration,IWebHostEnvironment env, MvcCore3_1Context context)
{
     this.actionContextAccessor = actionContextAccessor;
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    RotativaConfiguration.Setup(env.WebRootPath, "Rotativa");

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {               
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Privacy}/{id?}");

    });           
}

参考:

问题已解决。但我有点好奇。你的 class 名称是 MyController 但构造函数是 StudentsController.

public class MyController : Controller
    {
        
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly ActionContext _actionContext;

        public StudentsController(
           IWebHostEnvironment hostEnvironment,
           Acti

onContext actionContext)
        {
            
            _hostEnvironment = hostEnvironment;
            _actionContext = actionContext;
        }