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

Posted

技术标签:

【中文标题】尝试激活“Student.Controllers.MyController”时无法解析“Microsoft.AspNetCore.Mvc.ActionContext”类型的服务【英文标题】:Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.ActionContext' while attempting to activate 'Student.Controllers.MyController' 【发布时间】:2021-06-25 06:59:20 【问题描述】:

我正在尝试在我的控制器中使用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); 
        
    

【问题讨论】:

你能分享你的 Startup.cs 吗? @Rena 是的,当然.. @Rena 我需要使用 Microsoft.AspNetCore.Mvc.Infrastructure.IActionContextAccessor 来访问 ActionContext 吗? docs.microsoft.com/en-us/dotnet/api/… 是的。你需要在Startup.cs.BTW中注册它,它应该是在asp.net core 2.2之后的RotativaConfiguration.Setup(env.WebRootPath, "Rotativa");。也应该在app.UseStaticFiles();之后调用。 【参考方案1】:

问题解决了。但我有点好奇。你的类名是 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;
        

【讨论】:

其实Controller名字是StudentsController但是为了简单我改成MyController 忘记改构造函数名了,反正谢谢大家的观察【参考方案2】:

如下更改您的代码:

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?");

    );           

参考:

https://***.com/a/61864127/11398810

【讨论】:

以上是关于尝试激活“Student.Controllers.MyController”时无法解析“Microsoft.AspNetCore.Mvc.ActionContext”类型的服务的主要内容,如果未能解决你的问题,请参考以下文章

如何解决“尝试激活''时无法解析类型''的服务”

尝试激活 RedGate Multiscript 时“无法显示此页面”

.net Core 6 - 尝试激活时无法解析服务类型

片段已激活 - 尝试 setArguments 时

Laravel - 尝试创建帐户,登录并发送激活电子邮件正在抛出“尝试获取非对象的属性”

尝试打开Excel工作簿时,尝试/ Catch不会激活