Skip to content

Sending Data from Vue.js to C# REST API with Dapper and PostgreSQL

Hello everyone! How are you? Today, I wanted to delve into a topic that has been on my mind, which is sending data from Vue.js to a C# REST API. You know, like when you’re working on the frontend and need to send something to the backend. Sometimes, it can be confusing, right?

Especially when using technologies like Dapper and PostgreSQL, the process can become a bit more detailed. But believe me, it’s not that complicated after all. Having gone through these steps in my own projects, I know it might look intimidating at first. But step by step, you’ll see it’s a quite enjoyable process.

Thinking about it now, a few years ago, in one project, I was trying to send a user form I prepared with Vue.js to a C# API. Back then, I was just beginning to learn Dapper, and I was working with PostgreSQL quite intensively for the first time. My initial attempts were somewhat stumbling. The data would go, but it wouldn’t process correctly or would throw errors. I remember, my own API class was basically stuck :)) Anyway, I finally found the solution, of course.

So, what was the secret? Basically, the main idea is this: on the Vue.js side, you create a data structure, typically a JavaScript object. Then, you send this object to your backend API endpoint via an HTTP request, usually a POST. That’s it!

When Dapper and PostgreSQL are involved, on the backend, you need to receive this data and save it to the database. This is where Dapper’s advantages come into play. Dapper is a micro-ORM library developed for .NET. It allows you to run SQL queries directly and map the results to C# objects.

This process can be confusing even for someone who has some experience with both frontend and backend. You might think, ‘How does this data go from here to there?’ But once you understand that that JavaScript object is converted into a JSON string and that JSON is transformed into a C# object on the backend, everything falls into place.

Let’s move to the practical part. Suppose you have a user information object in Vue.js like this:

const userInfo = {     name: 'Ali',     surname: 'Veli',     email: 'ali.veli@example.com',     age: 30 };

You will send this object via a POST request from a Vue component or service. Using a library like Axios makes this process quite easy:

axios.post('/api/users', userInfo)     .then(response => {         console.log('Successfully saved!', response.data);     })     .catch(error => {         console.error('An error occurred:', error);     });

Note that this POST request is sent with content-type application/json. On the backend, we need to take this incoming JSON data and convert it into a C# object. In ASP.NET Core API projects, this usually happens automatically. That is, in your controller, the C# object you define as a parameter is directly bound to the incoming data.

Now, let’s get to the exciting part: how do we receive this data on the C# side and save it to PostgreSQL using Dapper? Let’s make a simple example:

First, define your C# model that represents the incoming data. It should match the JavaScript object on the frontend:

public class User {     public string Name { get; set; }     public string Surname { get; set; }     public string Email { get; set; }     public int Age { get; set; } }

Then, set up your database connection info and run your query with Dapper. Think of a controller action like this:

Here’s a simple controller action first, which I wrote to avoid common errors. It receives the User object and saves it to the database.

Now, the fun part: sending data to PostgreSQL with Dapper. You might consider code like this:

// WRONG EXAMPLE (Kept simple with string concatenation, but MUST NEVER do this!) // public async Task<IActionResult> PostUserWrong(User user) // { //     string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"; //     using (var connection = new NpgsqlConnection(connectionString)) //     { //         await connection.OpenAsync(); //         var sql = $"INSERT INTO Users (Name, Surname, Email, Age) VALUES ('{user.Name}', '{user.Surname}', '{user.Email}', {user.Age})"; //         await connection.ExecuteAsync(sql); //         return Ok("User successfully saved (Wrong Method).")); //     } // }

// CORRECT EXAMPLE (Parameterised query for SQL Injection protection) public async Task<IActionResult> PostUser(User user) { // In real projects, fetch connection string from config. var connectionString = "Server=localhost;Port=5432;Database=testdb;User Id=postgres;Password=your_password;"; using (var connection = new NpgsqlConnection(connectionString)) { await connection.OpenAsync(); var sql = @"INSERT INTO Users (Name, Surname, Email, Age) VALUES (@Name, @Surname, @Email, @Age)"; await connection.ExecuteAsync(sql, user); return Ok("User successfully saved."); } }

As you see, using Dapper’s ExecuteAsync method allows you to pass the user object directly as a parameter. This way, you are protected from SQL injection attacks. By the way, in my initial attempts, I used the unsafe string concatenation approach, which posed serious security risks. Luckily, those days are behind me.

For PostgreSQL, you need to have a table named Users with columns like Name, Surname, Email, and Age. After creating your database structure, the rest is straightforward.

By the way, if you’re interested in more detailed information about Dapper, there’s excellent documentation on GitHub, and you can find many tutorial videos on YouTube. Just search for dapper+postgresql+vuejs tutorial.

In conclusion, sending data from Vue.js to a C# REST API with Dapper and PostgreSQL offers a powerful and secure solution. Though it might look challenging at first when choosing the right technologies, following correct steps makes it very manageable. I believe this is one of the foundation stones of modern web development. What do you think? Do you often use such integrations?

If you want to try this, you can build your projects based on this fundamental setup. Remember, practice makes perfect! They say, “Learning to fish is better than being given fish,” and this is very similar. I think I have said enough. Also, if you’ve done similar integrations before or have questions, we can discuss in the comments. Sharing knowledge is always good. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.