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
Project ID:
1fec3643-c053-45ed-917f-90449a8054a5
@aleks you know .net right?
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
that question was directed towards the person i tagged
oh im sorry. thank you
i think they are a .net dev so when they have some time im sure theyll come by to help
gotchya. thanks so much brody!
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
?GitHub
azure-closet-app/backend/Program.cs at master · kristo-baricevic/az...
Contribute to kristo-baricevic/azure-closet-app development by creating an account on GitHub.
is that an ok way to send? it's too long to paste here
That's fine, thanks
You should be able to replace your
appsettings.json
connection string and your UseMySQL
call with this:
To load the connection details from the environmentok, 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?
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()
:
that goes into Program.cs
, and you can remove the stuff from appsettings.jsonok 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?
yep
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
What do the logs say?
GitHub
azure-closet-app/backend/Program.cs at master · kristo-baricevic/az...
Contribute to kristo-baricevic/azure-closet-app development by creating an account on GitHub.
that's just to show the changes you suggest ^^
I meant the deploy logs
oh ok one sec
add an extra parenthesis after the options.UseMySQL call
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
Whoops, I gave you false information, sorry. Try
app.Urls.Add
instead of app.UseUrls
.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/";
Do you have a
backend/Images
directory?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)
hmm
Uh, you don't seem to have that directory anywhere
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);
}
OK, I'm not sure - the error message suggests that you're trying to open it as a local file/directory
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);
}
},oh huh, that does seem to be what it's supposed to be doing
all this microsoft is making my brain hurt
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
😬 eek
well, I hope we can get your Railway problems figured out quickly
ty
im not sure what to try or how to really determine why its pulling a 404
AHA!
whatd you find
Well, I'm not sure exactly, but does your
UploadController
do anything that might cause this?not positive i dont think so bc it the upload endpoint wouldn’t get hit without pressing the upload button
actually, never mind, I can't find any file I/O anywhere
whereas the images controller gets called on render
It looks like the images controller isn't being hit
yeah i agree with that much. i can’t figure out why
It seems like it's falling back to static files for some reason
hmm
Try putting
UseStaticFiles
after UseEndpoints
in Program.cs
That's my first thought
Still odd though, if it was working on Azureyeah 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
also, here's a suggestion that I don't know what it means but apparently VSCode thinks you should do it:
why do you have so many unused using statements
honestly probably just doing a lot of trial and error stuff and forgetting to pull them out
fair enough
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
aleks went to bed
word thx
hmm
Never mind, docs actually say
UseStaticFiles
should be firstok 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?
I don't think your Railway deploy is using Actions.
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.
I'm honestly rather stumped, sorry.
no worries, thanks for tryin!