我正在使用 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();
}
}
现在,当我在 localhost 上运行它时,一切正常(也是注入 DataContext 的 API 控制器),但是当我将它发布到我的域时,来自注入 DataContext 的控制器的任何端点都返回一个 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 作为 db 上下文。
编辑:我设法通过添加一个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;
}
}
这是我得到的信息:
为 MediatR.IRequestHandler
2[Application.Reactivities.Activities.List+Query,System.Collections.Generic.List
1[Domain.Reactivities.Activity]] 类型的请求构造处理程序时出错。在容器中注册您的处理程序
什么可能导致发布的版本在使用 DataContext 时只表现出这样的行为并遇到此异常?
第二次编辑:我终于设法记录了我的内部异常,这里发生的事情是在生产中由于某种原因数据库(谷歌云 Sql 数据库)在连接时超时。