Honestly, these days I find myself once again wandering in the world of coding, as you know, I don’t have a super busy schedule right now, and I wanted to revisit some old topics to refresh my memory. Especially the subject of sending data from a frontend built with C# to REST APIs, you know, sometimes it gets overlooked or people wonder what modern approaches are, so I decided to revisit this topic. Particularly, I will talk about how to make data transfer from Vue.js to ASP.NET Core APIs more efficient using Dapper ORM.
You know, technology is always advancing. In the past, we would send a JSON string directly, then on the server side parse and process it. But now things seem to be a bit different. Especially with what ASP.NET Core has introduced, Dapper-like performance-oriented ORMs, it has made things a lot easier and faster, at least in my opinion.
Now you might say, ‘Come on, what are you talking about, we were already doing that!’ Yes, we were, but sometimes small details make a big difference, like fine-tuning. For example, how you send the data, how you handle it on the server, error management, and so on. By the way, I read somewhere recently about the importance of SSL certificates in such API communications—security should always be a priority, right?
Primarily, on the Vue.js side, we usually handle this with libraries like Axios. When making a simple POST request, the data model we send must be compatible with the server-side model. We used to do it manually, but now thanks to model binding, everything becomes much more automatic. It’s like a kind of magic, isn’t it?
On the ASP.NET Core side, we use controllers and action methods to receive the data. Bringing Dapper into play here is quite enjoyable. Instead of executing raw SQL queries, we delegate the queries to Dapper using parameters. This ensures better security and performance.
Now let’s get a bit more technical. In one of my projects, I was taking user information from a form and sending it to the API. The scenario involved fields like first name, last name, email, and password. Initially, I created a JSON object in Vue.js with Axios and sent it with a POST request. On the server side, I deserialize the incoming JSON directly into a C# class, and then I use this class with Dapper to save data into the database.
One time, I experienced an issue—I don’t remember exactly, but I was trying to cancel a subscription that cost around 15-20 Euro. I sent the form, but an error occurred on the server side. The data wasn’t processed correctly. Turns out, the key name in the JSON sent from Vue.js did not exactly match the field name in the C# model. A small case sensitivity mistake caused the whole system to get stuck 🙂
Anyway, such tiny errors make you more cautious. That’s when I realized how important it is to properly align the data model on the Vue.js side and create correct models on the C# side for incoming data. Especially when using Dapper, the parameter names in your query must match the property names of the model you send.
Now, let’s get into some code examples.
Vue.js Side (sending data with axios)
Here, we collect user data into an object and send it with Axios as a POST request. Think of it as a simple user registration.
// Vue Component (Example) methods: { async save() { const userData = { ad: this.ad, soyad: this.soyad, email: this.email, sifre: this.sifre // Security requires hashing! };try { const response = await axios.post('https://localhost:5001/api/kullanici', userData); // Use your API address console.log('Success:', response.data); alert('User successfully registered!'); } catch (error) { console.error('An error occurred:', error); alert('User could not be registered. Check the console for error details.'); } } }
Note that in `userData`, the property names must match the server-side model. Don’t let small mistakes like mismatched cases cause issues later 🙂
C# (ASP.NET Core) Side
Now, let’s define the model that will handle incoming data and the controller method to save data with Dapper.
First, define your model:
// Models/KullaniciModel.cs public class KullaniciModel { public string Ad { get; set; } public string Soyad { get; set; } public string Email { get; set; } public string Sifre { get; set; } // Should be hashed in real applications! }
Next, create your controller and use Dapper to perform the database insertion. Connection string details are omitted here; they should be configured in your `appsettings.json` file.
// Controllers/KullaniciController.cs [ApiController] [Route("api/[controller]")] public class KullaniciController : ControllerBase { private readonly IDbConnection _dbConnection; public KullaniciController(IConfiguration configuration) { // Retrieve connection string from appsettings.json var connectionString = configuration.GetConnectionString("DefaultConnection"); _dbConnection = new SqlConnection(connectionString); // For SQL Server // Use appropriate Dapper provider for other databases }
[HttpPost] public async Task PostKullanici([FromBody] KullaniciModel kullanici) { // Validation should be done here! if (!ModelState.IsValid) { return BadRequest(ModelState); }
// Query with Dapper var sql = @"INSERT INTO Kullanicilar (Ad, Soyad, Email, Sifre) VALUES (@Ad, @Soyad, @Email, @Sifre)"; // Table and column names may vary
try { // Parameters come directly from the model, Dapper understands this. await _dbConnection.ExecuteAsync(sql, kullanici); return Ok(new { message = "User successfully saved." }); } catch (Exception ex) { // In a real application, detailed logging should be used Console.WriteLine($"Error: {ex.Message}"); return StatusCode(500, new { message = "Failed to save user. An error occurred.", error = ex.Message }); } } }
That’s it! As you see, `[FromBody] KullaniciModel kullanici` automatically binds the incoming JSON to the `KullaniciModel` object, which you then pass directly to Dapper’s `ExecuteAsync` method as parameters. Doesn’t that make coding so much nicer?
Also, a tip—those simple proxy programs I used to write for testing and bypassing restrictions are long gone, but that’s a completely different story 🙂
This code example demonstrates a basic scenario. In a real project, passwords should definitely be hashed using libraries like BCrypt before saving. Validating incoming data with mechanisms like `ModelState.IsValid` is also very important. For more complex scenarios, you can use validation libraries like FluentValidation for detailed validation processes.
In conclusion, sending data from Vue.js to a C# REST API with Dapper is quite simple and performant. The key is ensuring your Vue.js data structure matches your C# model, and securely handling database operations. It’s fast, secure, and exactly what we want!