i’m trying to a Login controller in C# .Net Api but i keep getting error 400 Bad Requested and when tested in Postman i get the error Value cannot be null. (Parameter ‘s’)
This is the code.
Frontend Thunk (not sure if relevant)
export const loginUser = createAsyncThunk(
“account/Login”,
async ({ username, password }: { username: string; password: string }) => {
const response = await fetch(${API_BASE_URL}/api/account/login
, {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
},
body: JSON.stringify({ Username: username, Password: password }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Failed to login: ${errorData.message}`);
}
const data = await response.json();
return data;
}
);
My Controller
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginModel account)
{
try
{
if (account == null || string.IsNullOrEmpty(account.Password))
{
return BadRequest("Invalid request");
}
var user = await _context.Account.FirstOrDefaultAsync(a => a.Username == account.Username);
if (user == null)
{
return BadRequest("Invalid username or password.");
}
if (!BCrypt.Net.BCrypt.Verify(account.Password, user.Password))
{
return Unauthorized("Invalid password");
}
var token = GenerateJwtToken(user);
return Ok(new { token = token });;
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
My Login Model
namespace Server.AstralApi.api.Models
{
public class LoginModel
{
public required string Username { get; set; }
public required string Password { get; set; }
}
}
Rewrite the controller, verify the Model, and when the data it send from frontend it does have values
saintyves is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.