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

ASP.NET Core WebAPI报错:无法解析RoadWay_HistoryContext服务

问题原因

你的报错本质是ASP.NET Core内置的依赖注入容器,无法找到你定义的RoadWay_HistoryContext服务实例,所以在给StatewidesController构造函数注入参数时触发了异常,是EF Core接入.NET Core项目的常见入门问题。

解决方案

步骤1:配置连接字符串(可选但推荐)

先在项目根目录的appsettings.json文件中添加数据库连接配置,避免硬编码连接串到上下文代码里:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "RoadWayHistoryDB": "Server=dotb6gisdbst01;Database=RoadWay_History;Trusted_Connection=True;TrustServerCertificate=True;"
  },
  "AllowedHosts": "*"
}

加TrustServerCertificate=True是为了避免本地开发时SQL Server证书验证不通过的问题。

步骤2:在Startup中注册DbContext

打开Startup.cs,找到ConfigureServices方法,添加RoadWay_HistoryContext的注册逻辑:

public void ConfigureServices(IServiceCollection services)
{
    // 新增这一段注册DbContext
    services.AddDbContext<RoadWay_HistoryContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("RoadWayHistoryDB")));

    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "TestAPI", Version = "v1" });
    });
}

可选优化

你可以删掉RoadWay_HistoryContext中OnConfiguring方法里硬写的连接字符串逻辑,上下文注册时已经传入了配置,那段代码不会再触发,也避免了敏感信息硬编码的风险。

完成上面的操作后重新运行项目,再访问/api/Statewides接口就可以正常返回数据了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 08:57:04