Home > Blockchain >  Injecting DbContext to API controllers makes them return index.html instead of the actual result on
Injecting DbContext to API controllers makes them return index.html instead of the actual result on

Time:10-07

I am using a default ReactApp project from visual studio with net5 as framework. This by default comes with a WeatherApiController. Now the problem is, I created a DataContext (DbContext) which I am trying to inject in the 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();
    }
}

now when I run this on localhost, everything is working just fine (also the API controller with the DataContext injected), but when I publish it to my domain, any endpoint coming from a controller which has the DataContext injected returns a html file instead of actually working.

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

I added the DataContext as db context in Startup.cs.

Edit: I managed to get an exception by addin a try catch block as following:

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;
         }
}

And this is the message I get:

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

What could cause the published version only to behave like this and hit this exception when using the DataContext?

Second Edit: I finally managed to log my innerexception and what is going on here is that in production for some reason the database (Google Cloud Sql Database) is timing out on connect.

CodePudding user response:

My Google Cloud SQL database was not accepting my IP address as a valid IP for a connection, so my DataContext was not initializing.

This resulted in my handlers not being initialised correctly so once I added my IP to the allow list, the issue was resolved.

  • Related