将 DbContext 注入 API 控制器使它们成为 return index.html 而不是 NET5 React webapp 发布版本的实际结果

Injecting DbContext to API controllers makes them return index.html instead of the actual result on published version of NET5 React webapp

我正在使用来自 visual studio 的默认 ReactApp 项目,并将 net5 作为框架。这默认带有 WeatherApiController。现在的问题是,我创建了一个 DataContext (DbContext),我试图将其注入 ApiController。

[ApiController]
[Route("[controller]")]
public class ActivitiesController : ControllerBase
{
    private readonly DataContext _context;

    public ActivitiesController(DataContext context)
    {
        _context = context;
    }

    /// <summary>
    /// Returns an activity by id from the database
    /// </summary>
    /// <param name="id">Id of activity</param>
    /// <returns>Activity</returns>
    [HttpGet("{id}")]
    public Activity GetActivity(Guid id)
    {
        return new Activity { Category = "das", City = "city" };
    }

    [HttpGet]
    public IEnumerable<Activity> Get()
    {
        return _context.Activities.ToArray();
    }
}

现在,当我在本地主机上 运行 时,一切正常(还有注入了 DataContext 的 API 控制器),但是当我将它发布到我的域时,任何端点来自将 DataContext 注入 returns 一个 html 文件而不是实际工作的控制器。

 public class Startup
{
    private readonly IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllersWithViews();           

        // In production, the React files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });

        services.AddDbContext<DataContext>(options =>
        {
            options.UseMySql(_config.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(_config.GetConnectionString("DefaultConnection")));
        });
    }

    // 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("/Error");
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseRouting();

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

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });
    }
}

我在 Startup.cs 中添加了 DataContext 作为数据库上下文。

编辑:我设法通过添加一个 try catch 块来获得异常,如下所示:

public async Task<List<Activity>> Handle(Query request, CancellationToken cancellationToken)
{
         try
         {
                return await _context.Activities.ToListAsync();
         }
         catch (Exception ex)
         {
                List<Activity> activities = new List<Activity>();
                activities.Add(new Activity { Description = ex.Message });
                return activities;
         }
}

这是我收到的消息:

Error constructing handler for request of type MediatR.IRequestHandler2[Application.Reactivities.Activities.List+Query,System.Collections.Generic.List1[Domain.Reactivities.Activity]]. Register your handlers with the container

什么会导致发布的版本仅表现如此,并在使用 DataContext 时遇到此异常?

第二次编辑:我终于设法记录了我的 innerexception,这里发生的事情是在生产中由于某种原因数据库(Google 云 Sql 数据库)连接超时。

我的 Google 云 SQL 数据库不接受我的 IP 地址作为连接的有效 IP,所以我的 DataContext 没有初始化。

这导致我的处理程序没有正确初始化,所以一旦我将我的 IP 添加到允许列表,问题就解决了。