Session is not storing in react and Asp Dot Core Web API

133 views Asked by At

I had created a project using Asp .Net Core Web Api in Backend and React in front end.

While I register a user I need to store the user data in the session and after verfiying the user using a otp send to mobile number I need to save the data to database.

It works fine in swagger and Postman but it throws error in react

User Register Repository:

public async Task<UserDatum> Register(CreateUserDTO userDTO)
        {
            UserDatum userDatum = new UserDatum()
            {
                UserName = userDTO.UserName,
                FullName = userDTO.FullName,
                Email = userDTO.Email,
                PhoneNo = userDTO.PhoneNo,
                Address = userDTO.Address,
                Pincode = userDTO.Pincode,
                State = userDTO.State,

            };
            
            userDatum.Password = BCrypt.Net.BCrypt.HashPassword(userDTO.Password,10);
            userDatum.Role = "user";
            
            var smsSent = await _smsService.SendOTPSMS(userDTO.PhoneNo) ?? throw new Exception("Error sending in otp");
            userDatum.VerificationSid = smsSent;
            userDatum.IsOtpVerified = false;
            _httpContextAccessor.HttpContext.Session.SetString("UserData",JsonConvert.SerializeObject(userDatum));
            
            
            userDatum.Password = "";
            return userDatum;
            

        }

Verify OTP Repository:

public async Task<bool> VerifyOtp(string phoneNumber, string otp)
        {
            var userDataString = _httpContextAccessor.HttpContext.Session.GetString("UserData");
            if (string.IsNullOrEmpty(userDataString))
            {
                return false;
            }
            var userDatum = JsonConvert.DeserializeObject<UserDatum>(userDataString);

            var isVerified = await _smsService.CheckVerification(phoneNumber, otp, userDatum.VerificationSid);
            if (isVerified)
            {
                userDatum.IsOtpVerified = true;
                _context.UserData.Add(userDatum);
                await _context.SaveChangesAsync();
                _httpContextAccessor.HttpContext.Session.Remove("UserData");
                return true;
            }
            return false;

        }

React:

  const formik=  useFormik({
    initialValues:{
      username: "",
      fullName: "",
      email: "",
      phoneNo: "",
      address: "",
      pincode: "",
      state: "",
      password: "",
      confpassword: "",
    },
    validationSchema:validationSchema,
    
    onSubmit: async(values)=>{
      
      try{
        const {confpassword,...reqData} = values
         const response = await axios.post("https://localhost:7254/api/Users/register",
         reqData);
         console.log(response.data);
         setShowOTPModal(true);
      }
      catch(error){
        console.log(error.response);
        if(error.response && error.response.data && error.response.data.errorMessages &&error.response.data.IsSuccess==false ){
          const errorMessages = error.response.data.errorMessages;
          setErrorMessage(errorMessages);
          console.log(errorMessages);
        }
        else{
          setErrorMessage("An error occurred try again");
          console.log("An error occurred try again");
        }
      }
    
    }
  })

const formikOtp = useFormik({
    initialValues:{
      otp:"",
    },
    validationSchema:otpValidatinSchema,
    onSubmit:async (values)=>{
      console.log(typeof(formik.values.phoneNo));
      console.log(typeof(values.otp));
      try{
        const response = await axios.post("https://localhost:7254/api/Users/verify",{
        phoneNo:formik.values.phoneNo,
        otp:values.otp,
        });
        console.log(response.data);
        setShowOTPModal(false);
      }
      catch(error){
        
        console.log(error.response);
        if(error.response &&
          error.response.data &&
          error.response.data.errorMessages &&
          error.response.data.IsSuccess === false){
            const errorMessage = error.response.data.errorMessages;
            setErrorMessage(errorMessage);
            console.log(errorMessage); 
          }
          else{
            setErrorMessage("An error occurred please try again");
            console.log("An error occurred please try again");
          }
      }
    }
  })

What I found while I debug the code is that:

var userDataString = _httpContextAccessor.HttpContext.Session.GetString("UserData");
            if (string.IsNullOrEmpty(userDataString))
            {
                return false;
            }

It returns always false which means there is no session right?

Session Config in Program.cs:

builder.Services.AddDistributedMemoryCache();
            builder.Services.AddSession(options =>
            {
                options.Cookie.HttpOnly = false;
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.IsEssential = true;
                // Configure other session options
            });

How can I create and store the data in session using Dot Net Core Web API and React?

Did I need to create and store the data in react also?

0

There are 0 answers