R
Railway•16mo ago
kr1sto__

Unable to connect and interact with MySQL database in .NET deployment

Hello, this is for project: 1fec3643-c053-45ed-917f-90449a8054a5 I have an app I've deployed along with a MySQL database. I have confirmed the migrations went through and I can connect locally either with CLI or via local host. Upon deployment however, I am getting nothing but 404 errors. I have been working on debugging for a while and am not sure what to try next. My appsettings.json has the connection string as follows (password redacted): { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "RAILWAY_MYSQL_CONNECTIONSTRING": "Server=containers-us-west-68.railway.app;Port=7055;Database=railway;Uid=root;Pwd=**;" }, "TokenSecretKey": "secret_dandelion_disco" } My program.cs is using the following to make the connection: var connectionString = builder.Configuration.GetConnectionString("RAILWAY_MYSQL_CONNECTIONSTRING"); builder.Services.AddDbContext<ClothingInventoryContext>(options => options.UseMySQL(connectionString)); I have connected to MySQL via railway with node.js and Spring Boot apps in the past, without issue. But this one seems to be giving me trouble. Any help would be greatly appreciated! Thank you in advance for any time and assistance you can offer me here.
63 Replies
Percy
Percy•16mo ago
Project ID: 1fec3643-c053-45ed-917f-90449a8054a5
Brody
Brody•16mo ago
@aleks you know .net right?
kr1sto__
kr1sto__•16mo ago
Hi Brody, thanks for the response. Can you be more specific with your question? i've worked with it before, yes, and have built this app and deployed it to Azure. It worked fine on Azure as far as connectivity. But Azure was too expensive and I wanted to deploy to railway because my other apps are deployed here. Of course there's many moving parts with everything and I'm relatively new so there's certainly things beyond my knowledge base
Brody
Brody•16mo ago
that question was directed towards the person i tagged
kr1sto__
kr1sto__•16mo ago
oh im sorry. thank you
Brody
Brody•16mo ago
i think they are a .net dev so when they have some time im sure theyll come by to help
kr1sto__
kr1sto__•16mo ago
gotchya. thanks so much brody!
root
root•16mo ago
howdy, I know some .NET For starters, I'd recommend using the Railway-provided environment variables to connect to your DB instead of a static connection string But that shouldn't be causing a 404 error - could you send your whole Program.cs?
kr1sto__
kr1sto__•16mo ago
kr1sto__
kr1sto__•16mo ago
is that an ok way to send? it's too long to paste here
root
root•16mo ago
That's fine, thanks You should be able to replace your appsettings.json connection string and your UseMySQL call with this:
options.UseMySQL($"Server={Environment.GetEnvironmentVariable("MYSQLHOST")};Port={Environment.GetEnvironmentVariable("MYSQLPORT")};Database={Environment.GetEnvironmentVariable("MYSQLDATABASE")};Uid={Environment.GetEnvironmentVariable("MYSQLUSER")};Pwd={Environment.GetEnvironmentVariable("MYSQLPASSWORD")};")
options.UseMySQL($"Server={Environment.GetEnvironmentVariable("MYSQLHOST")};Port={Environment.GetEnvironmentVariable("MYSQLPORT")};Database={Environment.GetEnvironmentVariable("MYSQLDATABASE")};Uid={Environment.GetEnvironmentVariable("MYSQLUSER")};Pwd={Environment.GetEnvironmentVariable("MYSQLPASSWORD")};")
To load the connection details from the environment
kr1sto__
kr1sto__•16mo ago
ok, so the code you shared goes where the connection string variable currently is in appsettings? or wait no thats in program.cs and the variables get defined in appsettings.json?
root
root•16mo ago
But I'm pretty sure that the actual cause of the error is that you're listening on the wrong port - to fix that, add this call before app.Run():
app.UseUrls($"http://*:{Environment.GetEnvironmentVariable("PORT") ?? "80"}");
app.UseUrls($"http://*:{Environment.GetEnvironmentVariable("PORT") ?? "80"}");
that goes into Program.cs, and you can remove the stuff from appsettings.json
kr1sto__
kr1sto__•16mo ago
ok thanks ill give it a show now just to clarify on my end - does this method actually call the environment variables from the railway settings themselves to incorporate the actual values?
root
root•16mo ago
yep
kr1sto__
kr1sto__•16mo ago
wow cool ok deploying currently Failed to load resource: the server responded with a status of 404 () this is what happens with my initial fetch to the backend to establish communication
root
root•16mo ago
What do the logs say?
kr1sto__
kr1sto__•16mo ago
kr1sto__
kr1sto__•16mo ago
kr1sto__
kr1sto__•16mo ago
that's just to show the changes you suggest ^^
root
root•16mo ago
I meant the deploy logs
kr1sto__
kr1sto__•16mo ago
oh ok one sec
kr1sto__
kr1sto__•16mo ago
root
root•16mo ago
add an extra parenthesis after the options.UseMySQL call
root
root•16mo ago
kr1sto__
kr1sto__•16mo ago
thanks for catching that, one second its deploying 'WebApplication' does not contain a definition for 'UseUrls' and the best extension method overload 'HostingAbstractionsWebHostBuilderExtensions.UseUrls(IWebHostBuilder, params string[])' requires a receiver of type 'Microsoft.AspNetCore.Hosting.IWebHostBuilder' i got that, so i'm adding that using statement at the top of program.cs and trying again im getting this Error: D:\a\azure-closet-app\azure-closet-app\backend\Program.cs(113,1): error CS1929: 'WebApplication' does not contain a definition for 'UseUrls' and the best extension method overload 'HostingAbstractionsWebHostBuilderExtensions.UseUrls(IWebHostBuilder, params string[])' requires a receiver of type 'Microsoft.AspNetCore.Hosting.IWebHostBuilder' [D:\a\azure-closet-app\azure-closet-app\backend\closet.csproj] thats from the build log
root
root•16mo ago
Whoops, I gave you false information, sorry. Try app.Urls.Add instead of app.UseUrls.
kr1sto__
kr1sto__•16mo ago
trying now weird its telling me Error: D:\a\azure-closet-app\azure-closet-app\backend\Program.cs(113,5): error CS1955: Non-invocable member 'WebApplication.Urls' cannot be used like a method. [D:\a\azure-closet-app\azure-closet-app\backend\closet.csproj] but i don't have WebApplication.Urls' in my code rn any thoughts? i finally got it to deploy but its still getting the 404 i dont know if it's correct but a thread in SO had something like var port = Environment.GetEnvironmentVariable("PORT") ?? "80"; app.Run($"http://0.0.0.0:{port}"); it deployed with that but still getting 404 its saying in the logs: 2023/08/03 21:56:32 [error] 13#13: *4 open() "/app/backend/Images" failed (2: No such file or directory), client: 192.168.0.2, server: , request: "GET /backend/Images HTTP/1.1", host: "azure-closet-app-production.up.railway.app", referrer: "https://azure-closet-app-production.up.railway.app/"; which i don't get because that's the right route worked my way back, i think i got the code you provided to work but still getting 404 2023/08/03 23:31:55 [error] 22#22: *13 open() "/app/backend/Images" failed (2: No such file or directory), client: 192.168.0.2, server: , request: "GET /backend/Images HTTP/1.1", host: "azure-closet-app-production.up.railway.app", referrer: "https://azure-closet-app-production.up.railway.app/";
root
root•16mo ago
Do you have a backend/Images directory?
kr1sto__
kr1sto__•16mo ago
yeah this was hosted on azure a couple days ago and everything was working i just wanted to change it to railway because azure was super expensive (and slow)
root
root•16mo ago
hmm Uh, you don't seem to have that directory anywhere
kr1sto__
kr1sto__•16mo ago
i thought as opposed to a directory it was pointing the route of a controller which then directed it into the SQL table sorry to have misunderstood previous [ApiController] [Route("backend/Images")] public class ImagesController : ControllerBase { private readonly ClothingInventoryContext _dbContext; public ImagesController(ClothingInventoryContext dbContext) { _dbContext = dbContext; } [HttpGet] public IActionResult GetImages() { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); Console.WriteLine("userId retrieved", userId); var userClothingItems = _dbContext.UserClothingItems .Where(item => item.UserId == userId) .ToList(); var sharedClothingItems = _dbContext.ClothingItems.ToList(); var images = new List<object>(); foreach (var sharedClothingItem in sharedClothingItems) { images.Add(new { id = sharedClothingItem.Id, data = sharedClothingItem.Image, category = sharedClothingItem.Category, }); } foreach (var userClothingItem in userClothingItems) { images.Add(new { id = userClothingItem.Id, data = userClothingItem.Image, category = userClothingItem.Category, userId = userClothingItem.UserId, }); } return Ok(images); }
root
root•16mo ago
OK, I'm not sure - the error message suggests that you're trying to open it as a local file/directory
kr1sto__
kr1sto__•16mo ago
im not sure either, i thought that fetch pointed to an endpoint not a directory async fetchImages() { try { // Get the token from local storage const token = localStorage.getItem('token'); // Include the token in the request headers const headers = { Authorization: Bearer ${token}, }; const response = await fetch('/backend/Images', { headers }); const data = await response.json(); console.log("fetched images", data); // Check if each image has a 'userId' property to determine if it's a user image this.images = data.map((image) => ({ ...image, isUserImage: image.userId !== null, })); } catch (error) { console.error('Failed to fetch images:', error); } },
root
root•16mo ago
oh huh, that does seem to be what it's supposed to be doing all this microsoft is making my brain hurt
kr1sto__
kr1sto__•16mo ago
bro same ive been trying to figure this out for 2 days i had an account with digital ocean so i tried to deploy it on there. same exact thing the front end is loading and the backend is responding with the same 404s i dont understand because i havent changed any of the code since trying to redeploy it from azure to railway and now digital ocean but i can't use azure because it was taking a full 60 seconds to load on the "cheap" tier which was still over twice as much as railway
root
root•16mo ago
😬 eek well, I hope we can get your Railway problems figured out quickly
kr1sto__
kr1sto__•16mo ago
ty im not sure what to try or how to really determine why its pulling a 404
root
root•16mo ago
AHA!
kr1sto__
kr1sto__•16mo ago
whatd you find
root
root•16mo ago
Well, I'm not sure exactly, but does your UploadController do anything that might cause this?
kr1sto__
kr1sto__•16mo ago
not positive i dont think so bc it the upload endpoint wouldn’t get hit without pressing the upload button
root
root•16mo ago
actually, never mind, I can't find any file I/O anywhere
kr1sto__
kr1sto__•16mo ago
whereas the images controller gets called on render
root
root•16mo ago
It looks like the images controller isn't being hit
kr1sto__
kr1sto__•16mo ago
yeah i agree with that much. i can’t figure out why
root
root•16mo ago
It seems like it's falling back to static files for some reason
kr1sto__
kr1sto__•16mo ago
hmm
root
root•16mo ago
Try putting UseStaticFiles after UseEndpoints in Program.cs That's my first thought Still odd though, if it was working on Azure
kr1sto__
kr1sto__•16mo ago
yeah i dont remember changing that but it doesn’t mean it didn’t happen i stepped out to grab some food right quick but ill try that as soon as i get back, thanks for the suggestion that would make sense
root
root•16mo ago
also, here's a suggestion that I don't know what it means but apparently VSCode thinks you should do it:
root
root•16mo ago
why do you have so many unused using statements
kr1sto__
kr1sto__•16mo ago
honestly probably just doing a lot of trial and error stuff and forgetting to pull them out
root
root•16mo ago
fair enough
kr1sto__
kr1sto__•16mo ago
i've just been trying to get this thing up and populated with data and then i was gonna go back and start cleaning it up. i've been teaching myself as i go along and i haven't refined my methodology yet. it's kinda just felt like hustle hustle hustle bc i'm just building a portfolio i used C# to try and make myself available for more jobs but its out of my wheelhouse. i noticed the other day i had a lot of unsed using statements as well gonna try to swap that endpoint method rn changing those statements around unfortunately didn't affect anything good thought though re: the top level registration vs UseEndpoints, I can't find any evidence of that being the issue but I can't exactly tell could it be a firewall thing or perhaps the workflow\yml file
Brody
Brody•16mo ago
aleks went to bed
kr1sto__
kr1sto__•16mo ago
word thx
root
root•16mo ago
hmm Never mind, docs actually say UseStaticFiles should be first
kr1sto__
kr1sto__•16mo ago
ok right on i'm going to try to redo the workflow file because im publishing through gh actions and had it set up for azure. if that doesn't work i might try to build a clone manually, or clone an old version of the app, thinking that perhaps there's some environmental dependencies missing or something. i may also try to reconfigure it for azure to see if it still works there, because i haven't cancelled that account yet do you have a resource for setting up a github actions workflow file for railway?
root
root•16mo ago
I don't think your Railway deploy is using Actions.
kr1sto__
kr1sto__•16mo ago
oh interesting, does it connect to railway behind the scenes somehow? yeah I can see that it's deploying on railway even though the workflow has been failing. ok well I can rule that out thx so strange, i migrated back to azure and it works https://closet-webapp.azurewebsites.net/ check out how freaking slow the initial load is. not too mention it costs 100+ just to host I wish I understood what the difference is with the deployment! All I changed was the database connection info. Of course that included some MySQL dependency differences, but the core code is the same.
root
root•16mo ago
I'm honestly rather stumped, sorry.
kr1sto__
kr1sto__•16mo ago
no worries, thanks for tryin!
Want results from more Discord servers?
Add your server