Search code examples
c#reactjsjsonserializationdeserialization

Attempting to post object from frontend to backend. Serialize object in frontend and deserialize object in backend. React C#


        const [payload, setPayload] = useState({
            Email: null,
            Password: null
          });
        
          const handleSubmit = async (e) => {
            e.preventDefault();
            var json = JSON.stringify(payload);
              
            try {
              const { data } = await axios.post(
                "https://localhost:5001/api/User/Login",
                {
                  json
                }
              );
              console.log(data);
              ctxDispatch({ type: "USER_LOGIN", payload: data });
              localStorage.setItem("userInfo", JSON.stringify(data));
              toast.success("Login Successful");
              navigate("/");
            } catch (err) {
              toast.error(getError(err));
            }
          };
        
        
        [AllowAnonymous]
                [HttpPost("Login")]
                public async Task<ActionResult<UserDTO>> Login([FromBody] LoginDTO loginDTO)
                {
                    //LoginDTO loginDTO = Newtonsoft.Json.JsonConvert.DeserializeObject<LoginDTO>(input);
        
                    var pwd = Encrypt.ConvertToEncrypt(loginDTO.Password);
        
                    User currentUser = await _context.user.FirstOrDefaultAsync(user =>
                       user.Email.ToLower() == loginDTO.Email.ToLower()
                       &&`enter code here`
                       user.Password == pwd);
}
    
    
    public class LoginDTO
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

When I post this string to my backend it attempts to parse my string but fails at the first char {. When i send this string wrapped in quotes through swagger it passes with no issues. When i send this string through postman with no quotes wrapped around the string I get the same exact error as i get when posting through my frontend.


Solution

  • fix the action input parameters, you don't need to deserialize it , it will be deserialized by MVC

    public async Task< ....([FromBody] LoginDTO loginDto)
    

    and since you are sending a json string, add content type to axios

    axios.post('..your url', json, {
      headers: {
        // Overwrite Axios's automatically set Content-Type
        'Content-Type': 'application/json'
      }
    });