I can't produce my code despite the different questions and answers found on stackoverflow.
Here is my problem, I want to receive the Username and Password of the client to perform the verification (the equality is only for the example).
However the LoginPost variable is all the time null.
Furthermore I have difficulty understanding the best way to send the client an http code and json at the same time.
using Microsoft.AspNetCore.Mvc;
using web.Models;
namespace web.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class LoginController : ControllerBase
{
[HttpPost]
public ActionResult<LoginPost> LoginPost([FromBody] LoginPost loginPost)
{
// (1) FAIL, loginPost variable is null
if (loginPost.Username == loginPost.Password)
{
return loginPost;
}
// (2) How to add a message like "User/Password fails"
return Unauthorized();
}
}
}
Note the annotations (1) and (2) in the code.
Here's the jQuery code
$.ajax({
url: '../api/Login',
type: 'POST',
dataType: "json",
contentType: "application/json, charset=utf-8",
data: {
Username: username,
Password: password
},
statusCode: {
200: function (data) {
console.log(data);
}
401: function (data) {
console.log(data);
}
500: function (data) {
console.log(data);
}
}
});
and LoginPost.cs class:
public class LoginPost
{
public string Username { get; set; }
public string Password { get; set; }
}
[FromBody] LoginPostdata is all the timenull. I can't receive data by POST