Skip to content

C# .NET Integration with Vue.js: My Practical Coding Experiences and Tips

Last weekend, I went on a short family trip to Bursa with my wife and child, as you know, such plans are always finalized at the last minute. While sitting in the car, I got the idea for a new Vue project with a C# backend, but of course, I didn’t have time to code, so I just made a note of it in my mind. When I got home, I started implementing that idea, but on the first try, the API call in the Vue side crashed, giving a CORS error, I think, because I had forgotten to set up the middleware in the .NET startup. Anyway, I quickly fixed it and it worked, the family trip break seems to have refreshed my mind.

Yes, such small mistakes can drive you crazy, but they also provide learning opportunities. It’s a bit like mountaineering, you take a wrong step, but you go back and fix it, right?

Integrating frontend frameworks like Vue.js when developing REST APIs with C# .NET is an important part of my daily routine. I’ve been using this duo for years, and consuming an API fed by a PostgreSQL database in Vue is both fast and efficient. However, sometimes there are minor problems during integration, such as with authentication or data binding. In my opinion, the best approach is to use a lightweight ORM like Dapper, as Entity Framework can be heavy for small projects.

By the way, I just remembered, I switched from jQuery to Vue in a project last month, and now managing state with the Vuex store is much cleaner compared to dealing with AJAX calls back then. Are you still using vanilla JS or have you made the switch as well?

To set up the REST API on the C# side, you first start a .NET Core project, I usually choose the web API template instead of the console app. In the Startup.cs or Program.cs (in newer versions), you add the middlewares, and don’t forget CORS so that you can make calls from the Vue dev server. Here’s a simple example, you define an endpoint in the Controller:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IDbConnection _db;

    public ProductsController(IConfiguration config)
    {
        _db = new NpgsqlConnection(config.GetConnectionString("DefaultConnection"));
    }

    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        var products = await _db.QueryAsync<Product>("SELECT * FROM products");
        return Ok(products);
    }
}

Here I used Dapper’s QueryAsync, the PostgreSQL connection comes from the appsettings.json. The query is fast, with little overhead. But be careful, if you don’t write the connection string correctly, you’ll get an error, once I mixed up the localhost and the production server, and the data was lost.

On the Vue.js side, you install an HTTP client like axios, I prefer it over fetch as it’s more practical. In the App.vue or a component, you add a method like this:

import axios from 'axios';

export default {
  data() {
    return {
      products: []
    }
  },
  async mounted() {
    try {
      const response = await axios.get('https://localhost:5001/api/products');
      this.products = response.data;
    } catch (error) {
      console.error('API call failed:', error);
    }
  }
}

It was working great, until you forget HTTPS when deploying to production, and then you get a mixed content error. This is why you should make the base URL dynamic in the .env file, keeping separate ones for development and production. The best part of this integration is the reactive data binding, the list renders automatically with v-for, unlike the manual DOM manipulation days with jQuery.

Data Validation and Error Handling

Now let’s talk about data validation, in C# I use DataAnnotations for model validation, you add [Required] and such to the model. In Vue, you control it with computed properties on form submit.

In my experience, the most common errors occur in authentication, you forget to add the JWT token to the header. Set up the AddAuthentication middleware in .NET, and fetch the token from localStorage in Vue and put it in an axios interceptor. This way, you get a secure API, but make sure to test it manually in Postman as well.

Recently, I wrote a similar API for an embedded system project, pulling data from Arduino and sending it to a Vue dashboard. There I also faced a connection delay issue, the latency was high around 200-300 ms, but I optimized it.

I think the most important part is error handling, use try-catch blocks liberally but don’t overdo it. You can set up a global error handler in Vue, and add it to axios’s default. In my opinion, this way the user experience is not disrupted, just add loading spinners and such to keep the users waiting.

Performance Optimizations

Speaking of performance, add pagination to your API, otherwise, it will slow down with large data. In C#, use Skip-Take with Dapper queries, and in Vue, integrate a library for infinite scroll. Though sometimes I just put a simple pagination button, users are already used to it.

But you sometimes forget caching, add Redis or something to .NET, and use service workers for offline support in Vue. This way, the app becomes faster, and it makes a difference for mobile usage. Do you use caching or always fetch fresh data?

Honestly, I switch between PostgreSQL and MySQL depending on the project, the integration with Vue doesn’t differ much, but query optimization is important. Once I over-joined, and the query took 5 seconds, I was really annoyed.

(Don’t forget to check the database indexes!)

For deployment, I usually host the .NET API on Azure or Heroku, and the Vue app on Netlify. Setting up a CI/CD pipeline is a bit of a hassle, but once you do it, it’s smooth sailing. Actually, you can set up automatic deployment with GitHub Actions, it builds on push.

The beauty of this integration is scalability, you can scale as the user base grows. But don’t overengineer in the beginning, start with an MVP. In my projects, it’s always like that, first the basic API, then the Vue prototype, get feedback, iterate.

Anyway, let me give you a practical tip: manage environment variables properly, read them with IConfiguration in .NET, and process.env in Vue. If you misconfigure them, secrets will leak in production, so be careful.

In conclusion, the C# .NET and Vue.js duo is indispensable for me, you can quickly develop both the backend and frontend. If you’re new, check out the Microsoft Docs for the basics in .NET, and the official Vue site has great tutorials. For more examples, search Google for ‘C# .NET Vue.js integration examples’, there are plenty of code snippets. Also, the r/dotnet subreddit on Reddit has discussions, the community is helpful. I also remember seeing a detailed article on a tech blog, but I forgot the link.

I think that’s about it, it’s worth trying in my opinion. Share your experiences in the comments, maybe I can learn something new as well 🙂