【问题标题】:error in showing view of a controller in asp.net core MVC在 asp.net core MVC 中显示控制器视图时出错
【发布时间】:2020-01-27 12:17:41
【问题描述】:

我正在使用 asp.net 核心实现一个项目。我有几个控制器类。我通过 CRUD 方法创建了它们。我有一个名为“ApiapplicantsController”的控制器,它的相关模型 Apiapplicant 是 Api 和申请表的连接表。在启动文件中,我将以下表达式指定为 URL 模式:

 using System;
 using System.Collections.Generic;
 using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using CSDDashboard.Data;

namespace CSDDashboard
{
    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.AddControllersWithViews();

            services.AddDbContext<CSDDashboardContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment 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.UseRouting();

            app.UseAuthorization();

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

但是在运行项目并输入 URL 后,我收到以下错误:

处理请求时发生未处理的异常。 InvalidOperationException:无法解析类型的服务 'CSDDashboard.Models.CSSDDashboardContext' 尝试 激活“CSDDashboard.Controllers.ApiapplicantsController”。

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

我已经在 appsetting 文件中创建了我的连接字符串,并为它提供了一个名为 CSDDashboard 的变量名称。 appseting文件内容如下:

{
"AllowedHosts": "*",
"ConnectionStrings": {
"CSDDashboardContext": "Server=MOUSA-Z2;Database=CSSDDashboard;  Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
}
}

} 我的 DBContext 类名称是 CSSDDashboardContext。我已经通过 CRUD 方法创建了我所有的控制器类。 但是,我的控制器中只有一个使用 CSDDashboard 变量作为上下文类。当我运行项目并提供 URL 以调用 Vwreports 中的操作时,程序正常运行。

public class VwreportsController : Controller
  {
    private readonly CSDDashboardContext _context;         

public VwreportsController(CSDDashboardContext context)
    {
        _context = context;
    }

但在其他控制器中,CSDDashboard 是未知的,系统使用 CSSDDashboard 作为上下文,当我调用其中一个控制器时,会向我显示上述错误。下面为其他有错误的控制器之一提供了示例:

  public class ApisController : Controller
   {
    private readonly CSSDDashboardContext _context;

    public ApisController(CSSDDashboardContext context)
    {
        _context = context;
    }

如果有人帮助我解决问题,我将不胜感激。

【问题讨论】:

  • CSSDDashboardContext似乎没有被添加到服务集合中,所以DI容器在尝试初始化控制器时无法解析。
  • 感谢您的回复。如何将其添加到服务集合中?
  • 代码显示您已经将上下文添加到服务集合中
  • 那么,您对解决问题有什么其他建议吗?
  • 您发布的代码是否正确?我看到您将“CSDDashboardContext”添加到服务中,但没有将“CSSDDashboardContext”添加到服务中。有一个字符差异......您可能还想尝试更改“ConfigureServices”内容的顺序,以便在调用之前注入依赖项到“AddControllersWithViews”

标签: c# dependency-injection asp.net-core-mvc


【解决方案1】:

问题是您没有注入名为“CSSDDashboardContext”的类,而只是注入了名为“CSDDashboardContext”的类。

因此,所有在其构造函数中采用 CSDDashboardContext 的控制器都可以工作......而采用 CSSDDashboardContext 的控制器则不起作用。

您还需要注入 CSSDDashboardContext 类。

你需要像这样添加两个类:

      //this one you are already adding it according to your code
      services.AddDbContext<CSDDashboardContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));


     //Notice this is NOT the same class... Assuming this is a valid DBContext.  You need to add this class as well.
      services.AddDbContext<CSSDDashboardContext >(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));

【讨论】:

猜你喜欢
  • 2019-10-24
  • 2012-10-27
  • 2017-09-19
  • 1970-01-01
  • 2019-09-26
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
相关资源
最近更新 更多