Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am trying to execute a method from my MVC server side project when Register form's button is pressed from Angular Cli project. I have a user registration form on Angular. At the moment, I am able to post successfully the data typed in form's fields to my server's controller when the Register button is clicked. What I want to do is to insert the data, received through post request between client and server, into a SQLite DB. In my controller I have created a function (InsertUser) which does it, but I don't know hot to call this function on my Angular project. Could you please help me?

What I have tried:

The Angular ts file:

import { Component, OnInit, Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material';
import { Route, Router } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { HttpClient } from '@angular/common/http';
import { analyzeAndValidateNgModules } from '@angular/compiler';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  ngOnInit() {}
  
 data: any;

   constructor(private snackBar:MatSnackBar, private router: Router, private http:HttpClient){}

   onSubmitRegistration(users: {rEmail: string, rPassword: string, rRepeatPassword: string}){
      console.log(users);

          this.http.post('http://localhost:54111/RegisterController', users, {withCredentials: true}).subscribe(data => {
            console.log(data);
  })
      
   }

   login() {
    //login code
   }
 }

On MVC server side, the RegistrationController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;
using static ServerSide.Controllers.RegisterController;
using System.Data.SQLite;


namespace ServerSide.Controllers
{
    [Route("Register")]
    public class RegisterController : ApiController
    {
        SQLiteConnection conn;
        public class Data
        {
            public string user { get; set; }
            public string password { get; set; }
            public string repeatPass { get; set; }
        }
        Data d;


        [HttpPost, AllowCrossSite]
        [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
        [Route("api/Register/InsertUser")]
        public void InsertUser()
        {
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=C:\\ProiectVisualStudio\\Reporting_how-to-use-the-web-report-designer-in-javascript-with-angular-t566422-19.2.3-\\CS\\ServerSide\\App_Data\\RegisterDB.db; Version = 3; New = True; Compress = True; "))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    try
                    {
                        cmd.Connection = conn;
                        conn.Open();
                        //  string strSql = "INSERT INTO tbl_Users (User, Password, RepeatPassword) VALUES('Test1', 'Test2', 'Test3');";
                        string strSql = "INSERT INTO tbl_Users (User, Password, RepeatPassword) VALUES(" + d.user.ToString() + ", " + d.password.ToString() + ", " + d.repeatPass.ToString() + ");";
                        cmd.CommandText = strSql;

                        cmd.ExecuteNonQuery();
                        // do something…
                        conn.Close();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("***Eroare conexiune DB: " + ex + "/n");
                    }
                }
            }
        }

        [HttpPost, AllowCrossSite]
        [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
        [Route("api/Register/Posthdf")]
        public IHttpActionResult Posthdf(Data data)
        {
            if (!ModelState.IsValid) 
                return BadRequest("Date invalide");
            
            System.Diagnostics.Debug.WriteLine("***EmailRegister: " + data.user + "***");
            System.Diagnostics.Debug.WriteLine("***PasswordRegister: " + data.password + "***");
            System.Diagnostics.Debug.WriteLine("***RepeatPasswordRegister: " + data.repeatPass + "***");

            InsertUser(); //I have tried to call the function when the button is pressed
            return Ok(true);
        }
    }
}
Posted
Updated 12-Oct-22 2:52am
Comments
Richard Deeming 12-Oct-22 4:50am    
string strSql = "INSERT INTO tbl_Users (User, Password, RepeatPassword) VALUES(" + d.user.ToString() + ", " + d.password.ToString() + ", " + d.repeatPass.ToString() + ");";

So many problems in one line of code!

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation/interpolation to build a SQL query. ALWAYS use a parameterized query.

You're storing your users' passwords in plain text. Don't do that!
Secure Password Authentication Explained Simply[^]

And you're storing the "confirm password" value alongside the password, which makes no sense. You should only use that value to confirm that the user entered the same password twice, then store the salted hash of the password and throw away the "confirm password" value.
DrgIonuţ 12-Oct-22 4:57am    
Could you please offer me an answer regarding my question? I'm not interested at the moment about security. I want to be able to insert those data in DB when the button is clicked. Do you have any ideas about this issue?

1 solution

I don't know Angular at all, but it would appear that you're not telling it which method to call. You're telling it to call the controller, but not the method on it:
this.http.post('http://localhost:54111/RegisterController', ...

I suspect it should be this instead:
this.http.post('http://localhost:54111/RegisterController/Posthdf', ...

As everybody else has said, ALWAYS use parameterized queries, NEVER use string concatentation to build the SQL statement. Why? What happens if the username is "O'Brian"? Your query breaks and this can be used to destroy your database.

Why on earth are you storing the "repeatPassword"? It's not used for anything beyond verifying the user really did want what was typed to be the password.

Why are you calling .ToString, ... on strings? Sorry, that's a pet peeve of mine.

Oh, and you're storing passwords as plain text. Doing that can cost you a huge chunk of money in fines when you database is breached.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900