Hello @Dondon510 ,
Looking at your Blazor authentication struggle, I can see you're hitting some classic "learning curve" moments. Let me give you a different take on this that the other answers haven't covered.
What's Really Going On Here
You're basically trying to force a square peg into a round hole. Your User_Login.cs
approach works great for traditional ASP.NET Core apps, but Blazor has its own way of handling authentication that's fundamentally different.
The Antiforgery Thing
Yeah, just remove that <AntiforgeryToken />
line from your EditForm
. Blazor handles this automatically when you use EditForm
. It's one of those "gotcha" moments that trips up everyone new to Blazor.
The Database Connection
Your "Host can't be null" error is telling you your connection string is missing the Host parameter. Make sure it looks like:
Host=localhost;Port=5432;Database=yourdb;User ID=youruser;Password=yourpass;
The Real Problem Nobody's Talking About
Here's the thing - you're trying to use HttpContext
in a Blazor component, but Blazor components don't work like that. They run in the browser, so they don't have the same server-side context that traditional Razor Pages do.
A Different Approach
Instead of fighting with the current setup, consider this:
Option 1: Keep Your Existing Logic, But Move It
Create a separate API controller for your authentication:
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
// Your existing User_Login.cs logic here
// Return a token or session info
}
}
Then in your Blazor component, call this API instead of trying to use HttpContext
directly.
Option 2: Embrace Blazor's Way
Blazor has its own authentication system with AuthenticationStateProvider
. It's different from what you're used to, but it's actually pretty elegant once you get the hang of it.
Why This Approach is Different
The other answers focus on the surface-level fixes (remove the token, fix the connection string), but they don't address the core issue: you're trying to use server-side patterns in a client-side framework.
The key insight is that Blazor authentication is fundamentally different from traditional ASP.NET Core authentication, and you need to work with that difference rather than against it.
My Recommendation
For learning purposes, I'd suggest creating a fresh Blazor project with the "Individual Account" template. It'll give you a working authentication system to study, and you can see how the pros handle this stuff. Then you can adapt your existing User_Login.cs
logic to work within that framework.
I hope this helps you get things back on track quickly! If you agree with my suggestion, feel free to interact with the system accordingly!